gpt4 book ai didi

javascript - 如何使用 ES6 导入重新导入模块

转载 作者:行者123 更新时间:2023-11-30 06:15:25 25 4
gpt4 key购买 nike

我需要在每次运行时重新导入模块 integration-test/integration,因为该模块可以在运行时动态更改其中的代码。我将 NodeJS 与实验模块一起使用,以便能够运行 ES6 Javascript。

似乎 require 使您能够在使用以下代码 delete require.cache[require.resolve('./integration-test/integration.js') ]。我如何使用 ES6 导入复制它?

//FIXME delete cached module here
import("./integration-test/integration").then((module) => {
console.log('Importing integration');
stub = module;
if (module) resolve();
else reject();
});

我确实有一个非常不优雅的解决方案,我用一个新名称写了一个新文件,然后将其作为一个不同的模块导入,但是,这远不理想,如果可能的话我想避免它,因为内存泄漏问题。

最佳答案

您可以使用查询字符串来忽略缓存。参见 https://github.com/nodejs/help/issues/1399 .

这是示例代码。

// currentTime.mjs
export const currentTime = Date.now();
// main.mjs
(async () => {
console.log('import', await import('./currentTime.mjs'));

// wait for 1 sec
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('import again', await import('./currentTime.mjs'));

// wait for 1 sec
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('import again with query', await import('./currentTime.mjs?foo=bar'));
})();

使用 node --experimental-modules main.mjs 运行它。

$ node --experimental-modules main.mjs 
(node:79178) ExperimentalWarning: The ESM module loader is experimental.
import [Module] { currentTime: 1569746632637 }
import again [Module] { currentTime: 1569746632637 }
import again with query [Module] { currentTime: 1569746634652 }

如您所见,currentTime.mjs 被重新导入,并在使用查询字符串导入时将新值分配给 currentTime

关于javascript - 如何使用 ES6 导入重新导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56492656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com