diff --git a/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts b/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts index 29e62e0e5b6f2b..0f178bddaba633 100644 --- a/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts +++ b/packages/next/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts @@ -3,14 +3,28 @@ import { isWebpack5 } from 'next/dist/compiled/webpack/webpack' import { realpathSync } from 'fs' import path from 'path' +const originModule = require.resolve('next-server/server/require') + function deleteCache(filePath: string) { try { - delete require.cache[realpathSync(filePath)] + filePath = realpathSync(filePath) } catch (e) { if (e.code !== 'ENOENT') throw e - } finally { - delete require.cache[filePath] } + const module = require.cache[filePath] + if (module) { + // remove the child reference from the originModule + const parent = require.cache[originModule] + if (parent) { + const idx = parent.children.indexOf(module) + if (idx >= 0) parent.children.splice(idx, 1) + } + // remove parent references from external modules + for (const child of module.children) { + child.parent = null + } + } + delete require.cache[filePath] } const PLUGIN_NAME = 'NextJsRequireCacheHotReloader'