Given an ESM Node.js v23.10.0 project (package.json contains "type":"module"
), I want to require a file, then delete its cache, and require it again so that its source runs again.
I tried this:
mod.js
console.log('in mod.ts')
testcase.js
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
require('./mod.js')
const key = Object.keys(require.cache)[0]
delete require.cache[key]
require('./mod.js')
There are ways to do this in a CJS project such as this answer, but I can't figure out how to do it in an ESM project.
I expected to see the console log printed twice, but it only prints once.
Is there a way to successfully uncache a module and reload its body in this test case?
Given an ESM Node.js v23.10.0 project (package.json contains "type":"module"
), I want to require a file, then delete its cache, and require it again so that its source runs again.
I tried this:
mod.js
console.log('in mod.ts')
testcase.js
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
require('./mod.js')
const key = Object.keys(require.cache)[0]
delete require.cache[key]
require('./mod.js')
There are ways to do this in a CJS project such as this answer, but I can't figure out how to do it in an ESM project.
I expected to see the console log printed twice, but it only prints once.
Is there a way to successfully uncache a module and reload its body in this test case?
Share Improve this question edited Mar 31 at 22:06 user29889977 asked Mar 31 at 16:36 user29889977user29889977 1492 silver badges6 bronze badges 6 | Show 1 more comment1 Answer
Reset to default 2This relies on require(esm)
feature that previously was experimental and now is enabled in Node 23 by default. This would cause ERR_REQUIRE_ESM
error in previous Node versions.
mod.js with default extension and type: module
is evaluated as ES module with respective semantics regardless of how it's imported, while require.cache
is applied to CommonJS modules only.
In order to make it work as expected in Node project with type: module
mod.js needs to be evaluated as CommonJS, so it must be renamed to mod.cjs.
eval(readFileSync(…))
instead ofrequire
if that's your goal, but I doubt that). – Bergi Commented Mar 31 at 22:05