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

41 lines
1.1 KiB
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'
import { IS_BUNDLED_PAGE_REGEX } from '../../../next-server/lib/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
constructor() {
2016-10-23 18:42:13 +02:00
this.prevAssets = {}
}
apply(compiler: Compiler) {
compiler.hooks.afterEmit.tapAsync(
'NextJsUnlinkRemovedPages',
(compilation, callback) => {
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
2016-10-23 18:42:13 +02:00
Promise.all(
removed.map(async f => {
const path = join((compiler as any).outputPath, f)
try {
await unlink(path)
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
})
).then(() => callback(), callback)
}
)
2016-10-23 18:42:13 +02:00
}
}