简体   繁体   English

在 for-of-loop 中导入 ES6

[英]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?有没有办法在 ES6 中使用 for-of-loop(或另一个循环)导入和导出多个文件?

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
}

One of main features of ES modules is they can be statically analyzed. ES 模块的主要特性之一是它们可以进行静态分析。 For this reason import statement follows strict syntax - so does export .出于这个原因, import语句遵循严格的语法- 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.这允许在 IDE 和工具中准确地计算模块导入和导出。 This is useful for tree-shaking, for instance.例如,这对于摇树很有用。

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';

对于多个导入文件,我找到了这个解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM