The title says it all. I can access my module directly from the browser. But I can’t for the life of me figure out HOW to load it using import()
?
What is it that I’m completely missing about dynamic imports?
import(`http://localhost:9000/assets/my_module.js`)
.then(( module ) => {
console.log('loaded module:', module);
});
or
import(`./assets/my_module.js`) // <-- or ANY path combination whatsoever.
.then(( module ) => {
console.log('loaded module:', module);
});
2
Answers
Ok, so I just spent the better part of a day finding out that you cannot have 'dynamic' strings with import()!?
Doing this:
will not work, whereas:
will.
So import is not TRULY dynamic, bummer!
Dynamic imports allow you to asynchronously load modules when they are needed. However, there are a few things to consider:
Here’s how you can modify your code:
Make sure that my_module.js is structured as an ES module (export statements are used) and that it’s being served correctly by your server. Also, ensure that the path is correct relative to the current module.
If you’re still facing issues, ensure that your server is correctly configured to serve the module and that there are no errors in the module itself. Additionally, check your browser’s console for any error messages that might provide more insight into the problem.