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-06-21 18:28:41 +02:00
|
|
|
import { Compiler } from 'next/dist/compiled/webpack.js'
|
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
|
2019-05-29 13:57:26 +02:00
|
|
|
constructor() {
|
2016-10-23 18:42:13 +02:00
|
|
|
this.prevAssets = {}
|
|
|
|
}
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
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
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
this.prevAssets = compilation.assets
|
2016-10-23 18:42:13 +02:00
|
|
|
|
2019-05-29 13:57:26 +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
|
|
|
}
|
|
|
|
}
|