rsnext/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts
2019-06-24 09:48:26 -04:00

40 lines
1 KiB
TypeScript

import { Compiler, Plugin } from 'webpack'
import { realpathSync } from 'fs'
function deleteCache(path: string) {
try {
delete require.cache[realpathSync(path)]
} catch (e) {
if (e.code !== 'ENOENT') throw e
} finally {
delete require.cache[path]
}
}
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export class NextJsRequireCacheHotReloader implements Plugin {
prevAssets: any = null
apply(compiler: Compiler) {
compiler.hooks.afterEmit.tapAsync(
'NextJsRequireCacheHotReloader',
(compilation, callback) => {
const { assets } = compilation
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)
}
}
}
this.prevAssets = assets
callback()
}
)
}
}