skip to Main Content

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()?

enter image description here

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


  1. Chosen as BEST ANSWER

    Ok, so I just spent the better part of a day finding out that you cannot have 'dynamic' strings with import()!?

    Doing this:

    import(`../${dymamic-modulename}/index.js`).then( … ).catch( … );
    

    will not work, whereas:

    import(`../modulename/index.js`).then( … ).catch( … )
    

    will.

    So import is not TRULY dynamic, bummer!


  2. Dynamic imports allow you to asynchronously load modules when they are needed. However, there are a few things to consider:

    • Path Resolution: The path you provide to import() should be relative to the current module. If you’re trying to import a module from a different origin (like http://localhost:9000/assets/my_module.js), ensure that CORS (Cross-Origin Resource Sharing) is configured correctly on the server serving that module.
    • Module Type: Ensure that the module you’re trying to import is structured correctly. If it’s a regular JavaScript module (export statements are used), it should be importable using import(). If it’s not a module, or it’s a different module type (like CommonJS), you might need to use different methods to import it dynamically.
    • Error Handling: Always handle errors in your import statements. If there’s an issue with loading the module, it will be caught in the catch block.

    Here’s how you can modify your code:

    import('./assets/my_module.js')
        .then((module) => {
            console.log('loaded module:', module);
        })
        .catch((error) => {
            console.error('Error loading module:', error);
        });

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search