Skip to content

Commit

Permalink
fix memory leak in require.cache
Browse files Browse the repository at this point in the history
  • Loading branch information
sokra committed Apr 28, 2021
1 parent 2d6b560 commit 388f1c8
Showing 1 changed file with 17 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down

0 comments on commit 388f1c8

Please sign in to comment.