rsnext/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts
Connor Davis b73abc0a4b Delete using realpath in HMR cache (#6635)
This will allow symlinked assets to be removed from the cache as well

Fixes: #5620
2019-03-15 00:22:57 +01:00

37 lines
994 B
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()
})
}
}