Open LouisStAmour opened 5 years ago
To help mask the above webpack delete nastiness, I made a very simple wrapper using promises:
const importAndForget = filename => {
return import(filename).finally(() => {
delete require.cache[require.resolve(filename)];
});
};
which simplifies the above example to:
it('supports dynamic imports -- sweet', async () => {
importAndForget('../src/someFunc.js').then(module => {
const Q = module.__get__('Q');
expect(Q.queue.size).to.equal(0);
Q.queue.add('test');
expect(Q.queue.size).to.equal(1);
});
importAndForget('../src/someFunc.js').then(module => {
const Q = module.__get__('Q');
expect(Q.queue.size).to.equal(0);
});
});
Had a hard time making the filenames dynamic while still keeping things await-compatible, so I ended up with the following function hard-coded:
function loadSomeFunc() {
delete require.cache[require.resolve('../src/someFunc.js')];
return import('../src/someFunc.js');
}
which can be used as follows:
it('supports dynamic imports -- sweet', async () => {
let module = await loadSomeFunc();
let Q = module.__get__('Q');
expect(Q.queue.size).to.equal(0);
Q.queue.add('test');
expect(Q.queue.size).to.equal(1);
module = await loadSomeFunc();
Q = module.__get__('Q');
expect(Q.queue.size).to.equal(0);
});
Not sure if this is working as intended or just a happy byproduct of Babel improvements, but I was able to use rewire APIs not just with top-level ES6 imports but also with dynamic imports using ES6 import() syntax. And with webpack, I can remove cached modules to force their re-evaluation. An example (assuming
'../src/someFunc.js'
contains a top-level constQ
that it doesn't export, which in turn has a set namedqueue
):Very happy with how this is working out! :)
If it helps anybody, I'm using open-wc's Karma config with webpack config modified as follows (I've included the original open-wc Karma webpack config inline...):