我在文件中有一长串导出的常量。这是一段摘录:
...
export const COUNTER_INCREMENT_REQUESTED = 'COUNTER_INCREMENT_REQUESTED';
export const COUNTER_INCREMENT_REQUESTED_ASYNC = 'COUNTER_INCREMENT_REQUESTED_ASYNC';
export const COUNTER_DECREMENT_REQUESTED = 'COUNTER_DECREMENT_REQUESTED';
export const COUNTER_DECREMENT_REQUESTED_ASYNC = 'COUNTER_DECREMENT_REQUESTED_ASYNC';
...
有没有办法创建一个数组并循环遍历它,导出每个值?
const events = [
...
'COUNTER_INCREMENT_REQUESTED',
'COUNTER_INCREMENT_REQUESTED_ASYNC',
'COUNTER_DECREMENT_REQUESTED',
'COUNTER_DECREMENT_REQUESTED_ASYNC',
...
]
for(event of events) {
export ...
}
不,这是不可能的。
ES模块系统的一个显着特征是可以静态分析模块结构。这基本上可以防止以编程方式导出事物,因为它会破坏静态可分析性。
我确实通过将常量放在它自己的文件/模块中,然后将它们导入模块并在那里循环它们来管理变体。
constants.js
export const COUNTER_INCREMENT_REQUESTED = 'COUNTER_INCREMENT_REQUESTED';
export const COUNTER_INCREMENT_REQUESTED_ASYNC = 'COUNTER_INCREMENT_REQUESTED_ASYNC';
export const COUNTER_DECREMENT_REQUESTED = 'COUNTER_DECREMENT_REQUESTED';
export const COUNTER_DECREMENT_REQUESTED_ASYNC = 'COUNTER_DECREMENT_REQUESTED_ASYNC';
index.js
import * as actions from './constants';
...
let eventEmitters = {};
for(const action in actions ) {
...
}
export default eventEmitters;