Es6: Conditional & Dynamic Import Statements

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.

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.



Related Topics



Leave a reply



Submit