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