rsnext/packages/next/build/webpack/plugins/unlink-removed-pages-plugin.ts

36 lines
1,001 B
TypeScript
Raw Normal View History

2016-10-23 18:42:13 +02:00
import { join } from 'path'
import { promisify } from 'util'
import fs from 'fs'
2018-10-02 00:55:31 +02:00
import { IS_BUNDLED_PAGE_REGEX } from 'next-server/constants'
import {Compiler} from 'webpack'
2016-10-23 18:42:13 +02:00
const unlink = promisify(fs.unlink)
// Makes sure removed pages are removed from `.next` in development
export class UnlinkRemovedPagesPlugin {
prevAssets: any
2016-10-23 18:42:13 +02:00
constructor () {
this.prevAssets = {}
}
apply (compiler: Compiler) {
compiler.hooks.afterEmit.tapAsync('NextJsUnlinkRemovedPages', (compilation, callback) => {
2016-10-23 18:42:13 +02:00
const removed = Object.keys(this.prevAssets)
.filter((a) => IS_BUNDLED_PAGE_REGEX.test(a) && !compilation.assets[a])
2016-10-23 18:42:13 +02:00
this.prevAssets = compilation.assets
Promise.all(removed.map(async (f) => {
const path = join((compiler as any).outputPath, f)
2016-10-23 18:42:13 +02:00
try {
await unlink(path)
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
}))
.then(() => callback(), callback)
2016-10-23 18:42:13 +02:00
})
}
}