Skip to content
Advertisement

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.

Advertisement

Answer

We do have dynamic imports proposal now with ECMA. This is in stage 3. 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. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement