Is it possible to have conditional import statements like below?
if (foo === bar) { import Baz from './Baz'; }
I have tried the above but get the following error (from Babel) when compiling.
'import' and 'export' may only appear at the top level
Is it possible to have dynamic import statements like below?
for (let foo in bar) { if (bar.hasOwnProperty(foo)) { import Baz from `./${foo}`; } }
The above receives the same error from Babel whilst compiling.
Is this possible to do or is there something I am missing?
The reason I am trying to do this is that I have a lot of imports for a number of "pages" and they follow a similar pattern. I would like to clean up my code base by importing these files with a dynamic for loop.
If this is not possible then is there a better way to handle large number of imports in ES6?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool . It is evaluated and all side effects are completed before continuing.
Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. There are multiple different types of conditionals in JavaScript including: “If” statements: where if a condition is true it is used to specify execution for a block of code.
Conditional StatementsUse if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With