2016-10-23 18:42:13 +02:00
|
|
|
import { join } from 'path'
|
2019-02-22 20:49:30 +01:00
|
|
|
import { promisify } from 'util'
|
2018-03-30 16:59:42 +02:00
|
|
|
import fs from 'fs'
|
2018-10-02 00:55:31 +02:00
|
|
|
import { IS_BUNDLED_PAGE_REGEX } from 'next-server/constants'
|
2019-03-10 05:27:33 +01:00
|
|
|
import {Compiler} from 'webpack'
|
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
|
2019-03-10 05:27:33 +01:00
|
|
|
export class UnlinkRemovedPagesPlugin {
|
|
|
|
prevAssets: any
|
2016-10-23 18:42:13 +02:00
|
|
|
constructor () {
|
|
|
|
this.prevAssets = {}
|
|
|
|
}
|
|
|
|
|
2019-03-10 05:27:33 +01:00
|
|
|
apply (compiler: Compiler) {
|
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) => {
|
2019-03-10 05:27:33 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}))
|
2018-03-27 20:11:03 +02:00
|
|
|
.then(() => callback(), callback)
|
2016-10-23 18:42:13 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|