javascriptmoduleecmascript-6

How can I conditionally import an ES6 module?


I need to do something like:

if (condition) {
    import something from 'something';
}
// ...
if (something) {
    something.doStuff();
}

The above code does not compile; it throws SyntaxError: ... 'import' and 'export' may only appear at the top level.

I tried using System.import as shown here, but I don't know where System comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a deprecated docs page.


Solution

  • We do have dynamic imports as part of ECMAScript 2020. This is also available as babel-preset.

    Following is way to do conditional rendering as per your case.

    if (condition) {
        import('something')
        .then((something) => {
           console.log(something.something);
        });
    }
    

    This basically returns a promise. The resolution of promise is expected to have the module. The proposal also has other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.