2018-06-16 17:23:02 +00:00
|
|
|
// @flow
|
2016-10-23 16:42:13 +00:00
|
|
|
import { join } from 'path'
|
2018-06-16 17:23:02 +00:00
|
|
|
import promisify from '../../../lib/promisify'
|
2018-03-30 14:59:42 +00:00
|
|
|
import fs from 'fs'
|
2018-06-16 17:23:02 +00:00
|
|
|
import { IS_BUNDLED_PAGE_REGEX } from '../../../lib/constants'
|
2016-10-23 16:42:13 +00:00
|
|
|
|
2018-03-30 14:59:42 +00:00
|
|
|
const unlink = promisify(fs.unlink)
|
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
// Makes sure removed pages are removed from `.next` in development
|
2016-10-23 16:42:13 +00:00
|
|
|
export default class UnlinkFilePlugin {
|
2018-06-16 17:23:02 +00:00
|
|
|
prevAssets: any
|
2016-10-23 16:42:13 +00:00
|
|
|
constructor () {
|
|
|
|
this.prevAssets = {}
|
|
|
|
}
|
|
|
|
|
2018-06-16 17:23:02 +00:00
|
|
|
apply (compiler: any) {
|
2018-07-24 09:24:40 +00:00
|
|
|
compiler.hooks.afterEmit.tapAsync('NextJsUnlinkRemovedPages', (compilation, callback) => {
|
2016-10-23 16:42:13 +00:00
|
|
|
const removed = Object.keys(this.prevAssets)
|
2018-06-14 17:30:14 +00:00
|
|
|
.filter((a) => IS_BUNDLED_PAGE_REGEX.test(a) && !compilation.assets[a])
|
2016-10-23 16:42:13 +00:00
|
|
|
|
|
|
|
this.prevAssets = compilation.assets
|
|
|
|
|
|
|
|
Promise.all(removed.map(async (f) => {
|
|
|
|
const path = join(compiler.outputPath, f)
|
|
|
|
try {
|
|
|
|
await unlink(path)
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ENOENT') return
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}))
|
2018-03-27 18:11:03 +00:00
|
|
|
.then(() => callback(), callback)
|
2016-10-23 16:42:13 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|