Unverified Commit b4b68c0b authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Use assetEmitted hook instead of afterEmit (#14626)

Makes sure this works correctly with webpack 5.
parent bd24b70d
import { Compiler, Plugin } from 'webpack' import { Compiler, Plugin, version } from 'webpack'
import { realpathSync } from 'fs' import { realpathSync } from 'fs'
const isWebpack5 = parseInt(version!) === 5
function deleteCache(path: string) { function deleteCache(path: string) {
try { try {
delete require.cache[realpathSync(path)] delete require.cache[realpathSync(path)]
...@@ -11,30 +13,56 @@ function deleteCache(path: string) { ...@@ -11,30 +13,56 @@ function deleteCache(path: string) {
} }
} }
const PLUGIN_NAME = 'NextJsRequireCacheHotReloader'
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files. // This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export class NextJsRequireCacheHotReloader implements Plugin { export class NextJsRequireCacheHotReloader implements Plugin {
prevAssets: any = null prevAssets: any = null
previousOutputPathsWebpack5: Set<string> = new Set()
currentOutputPathsWebpack5: Set<string> = new Set()
apply(compiler: Compiler) { apply(compiler: Compiler) {
compiler.hooks.afterEmit.tapAsync( if (isWebpack5) {
'NextJsRequireCacheHotReloader', // @ts-ignored Webpack has this hooks
(compilation, callback) => { compiler.hooks.assetEmitted.tap(
const { assets } = compilation PLUGIN_NAME,
(_file: any, { targetPath }: any) => {
if (this.prevAssets) { this.currentOutputPathsWebpack5.add(targetPath)
for (const f of Object.keys(assets)) { deleteCache(targetPath)
deleteCache(assets[f].existsAt) }
} )
for (const f of Object.keys(this.prevAssets)) {
if (!assets[f]) { compiler.hooks.afterEmit.tap(PLUGIN_NAME, () => {
deleteCache(this.prevAssets[f].existsAt) for (const path of this.previousOutputPathsWebpack5) {
} if (!this.currentOutputPathsWebpack5.has(path)) {
deleteCache(path)
} }
} }
this.prevAssets = assets
callback() this.previousOutputPathsWebpack5 = new Set(
this.currentOutputPathsWebpack5
)
this.currentOutputPathsWebpack5.clear()
})
return
}
compiler.hooks.afterEmit.tapAsync(PLUGIN_NAME, (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()
})
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment