Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 import in for-of-loop

Is there any way to import and export multiple files using for-of-loop (or another loop) in ES6?

const moduleNames = ['NumberUtils', 'StringUtils', 'ArrayUtils', 'MyModule', 'AnotherModule', 'BaseModule']

let modules = {}

for (const moduleName of moduleNames) {
    import module from './' + moduleName
    modules.moduleName = module
}

export modules

Without loop I have to write:

import NumberUtils from './NumberUtils'
import StringUtils from './StringUtils'
import ArrayUtils from './ArrayUtils'
import MyModule from './MyModule'
import AnotherModule from './AnotherModule'
import BaseModule from './BaseModule'

export {
    NumberUtils,
    StringUtils
    ArrayUtils
    MyModule
    AnotherModule
    BaseModule
}
like image 893
Vesmy Avatar asked Sep 16 '17 11:09

Vesmy


People also ask

Is for in loop ES6?

for…in The for…in loop is used to loop through an object's properties. In each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties.

How do you write a for loop in ES6?

The for...in loop is used to loop through an object's properties. Following is the syntax of 'for…in' loop. In each iteration, one property from the object is assigned to the variable name and this loop continues till all the properties of the object are exhausted.


1 Answers

One of main features of ES modules is they can be statically analyzed. For this reason import statement follows strict syntax - so does export. A snippet 'without loop' is the way it has to be done.

This allows to figure out module imports and exports exactly in IDEs and tools. This is useful for tree-shaking, for instance.

like image 53
Estus Flask Avatar answered Sep 23 '22 14:09

Estus Flask