2019-06-24 15:48:26 +02:00
|
|
|
import { Compiler, Plugin } from 'webpack'
|
2019-03-15 00:22:57 +01:00
|
|
|
import { realpathSync } from 'fs'
|
2019-03-10 05:27:33 +01:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
function deleteCache(path: string) {
|
2019-03-15 00:22:57 +01:00
|
|
|
try {
|
|
|
|
delete require.cache[realpathSync(path)]
|
2019-05-29 13:57:26 +02:00
|
|
|
} catch (e) {
|
2019-03-15 00:22:57 +01:00
|
|
|
if (e.code !== 'ENOENT') throw e
|
|
|
|
} finally {
|
|
|
|
delete require.cache[path]
|
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
|
2019-03-15 00:22:57 +01:00
|
|
|
export class NextJsRequireCacheHotReloader implements Plugin {
|
|
|
|
prevAssets: any = null
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
apply(compiler: Compiler) {
|
|
|
|
compiler.hooks.afterEmit.tapAsync(
|
|
|
|
'NextJsRequireCacheHotReloader',
|
|
|
|
(compilation, callback) => {
|
|
|
|
const { assets } = compilation
|
2018-07-24 11:24:40 +02:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
if (this.prevAssets) {
|
|
|
|
for (const f of Object.keys(assets)) {
|
|
|
|
deleteCache(assets[f].existsAt)
|
|
|
|
}
|
|
|
|
for (const f of Object.keys(this.prevAssets)) {
|
|
|
|
if (!assets[f]) {
|
|
|
|
deleteCache(this.prevAssets[f].existsAt)
|
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
}
|
2019-05-29 13:57:26 +02:00
|
|
|
this.prevAssets = assets
|
2018-07-24 11:24:40 +02:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
callback()
|
|
|
|
}
|
|
|
|
)
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
}
|