ES6 import in for-of-loop

2020-04-02 08:10发布

问题:

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
}

回答1:

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.



回答2:

I think that better and more clear way to do it is to create an index file and then import multiple components in one import.

//index.js
import PopUp from './PopUp';
import ToggleSwitch from './ToggleSwitch';

export {
  PopUp,
  ToggleSwitch
};

//app.js

import { PopUp, ToggleSwitch } from './components';


回答3:

For multiple import files I found this solution:

const files = require.context('../myFolder', true, /(Module|Utils)\.js$/)