How to reimport module with ES6 import

谁说胖子不能爱 提交于 2021-01-27 14:18:45

问题


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.

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.


回答1:


You can use query string to ignore cache. See https://github.com/nodejs/help/issues/1399.

Here is the sample code.

// 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'));
})();

Run this with 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 }

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



来源:https://stackoverflow.com/questions/56492656/how-to-reimport-module-with-es6-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!