Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: Conditional & Dynamic Import Statements

Conditional

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 

Dynamic

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?

Reasoning

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?

like image 603
Enijar Avatar asked Mar 10 '16 11:03

Enijar


People also ask

What is ?: In JavaScript?

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.

Is conditional an operator?

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.

What is a conditional in JavaScript?

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.

How do you use a conditional statement?

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.


1 Answers

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.

like image 129
thecodejack Avatar answered Sep 21 '22 13:09

thecodejack