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
How to Add Conditional Attribute in Angular 2
Generating Non-Repeating Random Numbers in Js
JavaScript - How to Detect If Document Has Loaded (Ie 7/Firefox 3)
How to Execute Promises Sequentially, Passing the Parameters from an Array
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
Most Efficient Way to Concatenate Strings in JavaScript
Invoking a Function Without Parentheses
How to Filter (Key, Value) with Ng-Repeat in Angularjs
React Hooks Usestate() with Object
(![]+[])[+[]]... Explain Why This Works
Convert String in Dot Notation to Get the Object Reference
Difference Between "Change" and "Input" Event for an 'Input' Element
Typeerror: Console.Log(...) Is Not a Function
Serializing Object That Contains Cyclic Object Value
Difference Between JSON.Stringify and JSON.Parse