admin管理员组

文章数量:1200961

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

I can't seem to get the syntax correct to end up with constants.foo

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

I can't seem to get the syntax correct to end up with constants.foo

Share Improve this question asked Aug 28, 2018 at 0:29 Samuel GoldenbaumSamuel Goldenbaum 18.9k20 gold badges71 silver badges111 bronze badges 1
  • stackoverflow.com/questions/43937561/… – João Otero Commented Aug 28, 2018 at 0:42
Add a comment  | 

3 Answers 3

Reset to default 12
import constants from './constants'

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

If you would like to import the constants directly from ./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; 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';, 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:

  • When should I use curly braces for ES6 import?
  • What is "export default" in javascript?
export default {
foo: 'foo',
bar: 'bar'
}

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

Then 
const.foo

本文标签: javascriptCorrect syntax to import constants in ES6Stack Overflow