使用 ES2015 语法,我们有了新的导入语法,我一直在尝试弄清楚如何将从一个文件导出的所有内容导入到另一个文件中,而不将其包装在对象中,即。可用,就好像它们是在同一文件中定义的一样。
所以,本质上是这样的:
// constants.js
const MYAPP_BAR = 'bar'
const MYAPP_FOO = 'foo'
// reducers.js
import * from './constants'
console.log(MYAPP_FOO)
这不起作用,至少根据我的 Babel/Webpack 设置,此语法无效。
替代方案
这可行(但是如果您需要导入多个内容,那么它又长又烦人):
// reducers.js
import { MYAPP_BAR, MYAPP_FOO } from './constants'
console.log(MYAPP_FOO)
与此相同(但它将常量包装在对象中):
// reducers.js
import * as consts from './constants'
console.log(consts.MYAPP_FOO)
第一个变体是否有语法,或者您是否必须按名称导入每个内容,或使用包装器对象?
最佳答案
您无法通过第一个变体的通配符导入所有变量,因为如果不同文件中的同名变量会导致变量冲突。
//a.js
export const MY_VAR = 1;
//b.js
export const MY_VAR = 2;
//index.js
import * from './a.js';
import * from './b.js';
console.log(MY_VAR); // which value should be there?
因为这里我们无法解析MY_VAR
的实际值,所以这种导入是不可能的。
对于您的情况,如果您有很多值要导入,最好将它们全部导出为对象:
// reducers.js
import * as constants from './constants'
console.log(constants.MYAPP_FOO)
关于javascript - 如何导入使用 ES2015 语法的文件导出的所有内容?有通配符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554526/