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
}
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.
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.
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.
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