简体   繁体   English

更正语法以在ES6中导入常量

[英]Correct syntax to import constants in ES6

Given the following modules, how do I import the constants module and avoid having the default property included: 给定以下模块,如何导入常量模块并避免包含默认属性:

// constants.es6
export default {
    foo: 'foo',
    bar: 'bar'
}

// anotherModule.es6
import * as constants from './constants';

results in constants.default.foo 结果为constants.default.foo

I can't seem to get the syntax correct to end up with constants.foo 我似乎无法正确语法以constants.foo结束

import constants from './constants'

console.log(constants.foo, constants.bar)

If you would like to import the constants directly from ./constants 如果您想直接从./constants导入常量

constants.js:
export const foo = 'foo'
export const bar = 'bar'

anotherModule.js:
import {foo, bar} from './constants'

console.log(foo,bar)

You shouldn't use an object for defining constants. 您不应该使用对象来定义常量。 Calling code is free to do constants.foo = 42; 调用代码可以随意执行constants.foo = 42; and change the value. 并更改值。

Use 采用

export const foo = 'foo';
export const bar = 'bar';

instead. 代替。

Then the import statement you have, import * as constants from './constants'; 然后,您拥有import语句, import * as constants from './constants'; , will work as well. ,同样可以使用。


If you don't want to change the way you define the constants, then your question is rather "how do I import a default export" , which is answered in these questions: 如果您不想更改定义常量的方式,那么您的问题就是“如何导入默认导出” ,这些问题可以回答:

export default {
foo: 'foo',
bar: 'bar'
}

// anotherModule.es6
import const from './constants';

Then 
const.foo

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

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