admin管理员组文章数量:1353662
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.
本文标签: javascriptHow do you uncache a module in Nodejs when using createRequireStack Overflow
版权声明:本文标题:javascript - How do you uncache a module in Node.js when using createRequire? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743934123a2564376.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
eval(readFileSync(…))
instead ofrequire
if that's your goal, but I doubt that). – Bergi Commented Mar 31 at 22:05