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

gregam3

我需要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时,它将被重新导入并分配给新值

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章