2017-09-16 95 views
2

有什麼方法可以在ES6中使用迴路(或其他迴路)導入和導出多個文件?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 

沒有環路我必須寫:

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 
} 
+0

你可以做'從「./NumberUtils」出口{默認爲NumberUtils};'僅供參考,這使得這些類型的列表更容易保持。爲什麼添加一行代碼比向數組添加項目更困難? – loganfsmyth

回答

1

對於多個導入文件,我發現這個解決方案:

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

之一的ES模塊的主要特點是,他們可以靜態分析。爲此import聲明如下strict syntax - export也是如此。一個「沒有循環」的片段是它必須完成的方式。

這可以準確計算出IDE和工具中的模塊導入和導出。例如,這對於樹木搖晃很有用。

1

我認爲更好更清晰的方法是創建一個索引文件,然後在一次導入中導入多個組件。

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

export { 
    PopUp, 
    ToggleSwitch 
}; 

//app.js 

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