问题
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