最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何通过ES6导入重新导入模块

运维笔记admin15浏览0评论

如何通过ES6导入重新导入模块

如何通过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/nodejs/help/issues/1399。

这里是示例代码。

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

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

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

node --experimental-modules main.js运行(不要忘记在"type": "module"中指定package.json)。

$ node --experimental-modules main.js 
(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.js被重新导入,并且在通过查询字符串导入时将新值分配给currentTime

发布评论

评论列表(0)

  1. 暂无评论