javascript - 如何使用 ES6 导入重新导入模块
问题描述
我需要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 - jquery show not working with href tel 点击android chrome
- react-native - 如何在 React Native 中创建不可阻挡的服务
- cplex - 如何修复 IBM CPLEX 上的内部错误?
- wordpress - 通过复选框选择多个类别,并显示属于这些类别的文章
- python - def show_batch() 没有显示我的火车图像
- react-native - 当 socket.io 更新新消息时,React Native Gifted Chat 会附加消息两次
- javascript - 在 three.js 中使用模板缓冲区
- vuejs2 - 将 ID 传递给 Quasar 并在默认设置中使用带有子组件的守卫
- javascript - TypeScript - 一遍又一遍地调用 API 端点,直到我们得到想要的结果 - 递归还是循环?
- android - Android EpoxyRecyclerView - 切换方向