Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18909

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

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

Upvotes: 8

Views: 24062

Answers (3)

nbwoodward
nbwoodward

Reputation: 3156

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)

Upvotes: 12

Felix Kling
Felix Kling

Reputation: 816404

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:

Upvotes: 8

Ravi Rane
Ravi Rane

Reputation: 159

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

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

Then 
const.foo

Upvotes: 1

Related Questions