rsnext/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts
Guy Bedford bd8f3c625f
ncc Webpack build (#7301)
* add back ncc

* fixup ncc build
2019-05-16 11:55:54 -05:00

37 lines
1,013 B
TypeScript

import { Compiler, Plugin } from 'next/dist/compiled/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()
})
}
}