I have many apps using dynamic import of javascript modules working for years.
Since today they are no longer working on chrome for windows.
The code line
const def = await import("../main.mjs");
is never returning nor throwing an exception (Its surrounded by try/catch)
On all other Browsers its still working fine.
Any suggestions?
1
I have the same issue and am currently looking into it further. So far I’ve found it’s somehow linked the imported file, importing other files.
Testing with this:
const modTest = await import('./test.js');
modTest.default('hello');
This version of test.js never resolves.
// test.js
import testFn from './test-copy.js';
export default function mainFn(str) {
console.log('MOD:', str);
testFn('hello');
}
This version of test.js works.
// test.js
export default function mainFn(str) {
console.log('MOD:', str);
}
This is not the full story however. I tried reproducing this issue in a blank project and haven’t had any luck.
UPDATE:
I found a fix for our specific case.
So it looks like top level awaits mess up dynamic imports that have their own imports.
Here is my test setup:
Basic HTML
...
<script defer src="one.js" type="module"></script>
...
// one.js
export default async function main() {
document.querySelector('.for-one').textContent = 'hello one';
const module = await import('./two.js');
await module.default();
}
export const twoMsg = 'hello two'
main()
const res = await fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes');
// two.js
import { twoMsg } from './one.js';
export default async function main(str) {
document.querySelector('.for-two').textContent = twoMsg;
}
If run like this, the function from two.js
is never run, as the promise of the import is never resolved. However if I remove the top-level await fetch
from one.js
it all works fine. So this issue can be solved by wrapping the whole thing in an async function.
This is probably a bug in chrome since top-level awaits should be supported in modules: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#browser_compatibility
One thing is still a bit confusing though… The line in our project where we encounter this issue uses the exact same code as in two other projects but those other two have no issues. Which leads me to believe this goes deeper. But I won’t dig anymore, the issue can be worked around for our case.
2