How to Conditionally Import an Es6 Module

How can I conditionally import an ES6 module?

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.

ES6: Conditional & Dynamic Import Statements

We do have dynamic imports proposal now with ECMA. This is in stage 2. This is also available as babel-preset.

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

if (foo === bar) {
import('./Baz')
.then((Baz) => {
console.log(Baz.Baz);
});
}

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

Conditional Import external package with ESLint

ES6 Modules are static. This means that import/export can not appear inside functions, conditional statements or contain variables. import/export statements are designed to be statically analyzable, so if you conditionally want to import something, that requires running logic and thus it cannot be parsed without running the application.

More info about it https://exploringjs.com/es6/ch_modules.html#static-module-structure

Can one conditionally import a module in NodeJS/React?

You can use Dynamic Imports to achieve this.
Like:

const A = condition && import('./a.js')

Although to use dynamic imports you will have to use babel.



Related Topics



Leave a reply



Submit