如何使用ES6导入重新导入模块 [英] How to reimport module with ES6 import

查看:65
本文介绍了如何使用ES6导入重新导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to reimport module integration-test/integration upon every run as this module can have code dynamically changed in it at run time. I am using NodeJS with experimental modules in order to be able to run ES6 Javascript.

似乎 require 使您可以在使用以下代码对模块进行删除后删除它们. delete require.cache [require.resolve('./integration-test/integration.js')] .如何使用ES6导入复制此内容?

It seems require enables you to delete modules after you require them with the following code delete require.cache[require.resolve('./integration-test/integration.js')]. How do I replicate this with ES6 import?

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

对于这个问题,我确实有一个非常巧妙的解决方案,我用新名称编写了一个新文件,然后将该文件导入为另一个模块,但是,这远不理想,并且由于可能而希望避免使用它内存泄漏问题.

I do have a very inelegant solution to this in which I write a new file with a new name and then import that as a different module, however, this is far less than ideal and would like to avoid it if possible due to the memory leak issues.

推荐答案

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

You can use query string to ignore cache. See 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 .

As you can see, currentTime.mjs is reimported and the new value is assigned to currentTime when it is imported with query string.

这篇关于如何使用ES6导入重新导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆