2017-04-03 34 views
2

我想提出很多常量像一個文件:如何`在JavaScript中導出默認*`?

constants.js

export const FOO = 'foo' 
export const BAR = 'bar' 

而且我可以導入它們喜歡:

index.js

import { FOO, BAR } from './constants.js' 

但是webpack警告我export default不是在./constants.js發現,這也意味着我不能做到這一點:

import constants from './constants.js' 

我已經嘗試做

export default * 

就像

import * from './constants' 

但它不工作。那麼有沒有什麼優雅的方法來代替以下內容?

export default { FOO, BAR } 
+0

我有'出口常量FOO = '富' 出口const BAR ='bar'',它工作得很好,我正在使用webpack。 –

回答

0

有它自己的常量目錄, 它有一個index.js做常量:

export * from './constants'; 

然後它會工作,我想

2

如果你不想做解構導入,那麼這些可能是你使用的兩個最佳選擇。

選項1

// constants.js 
export const FOO = 'foo' 
export const BAR = 'bar' 


// index.js 
import * as constants from './constants' 
/* 
* constants = { FOO: 'foo', BAR: 'bar' } 
*/ 

選項2

// constants.js 
export default { 
    FOO: 'foo', 
    BAR: 'bar' 
} 

//index.js 
import constants from './constants' 
0

設置你所有的常量被導出到文件: file.js

export const A; 
export const B; 
export const C; 

而且從單個文件導出它們:

export_file.js

export * from './file'; 

所以,你可以全部導入:
import_file.js

import * from './export_file';