6

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

Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104

3 Answers3

9
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)
nbwoodward
  • 2,816
  • 1
  • 16
  • 24
  • 1
    import constants from './constants' doesn't seem to import as expected. seems to need the * - import * as constants from './constants' – Samuel Goldenbaum Aug 28 '18 at 01:04
7

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:

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Of course you will still have the same problem if you are exporting an object. In general you can prevent callsites from mutating an object value by calling `Object.freeze` (recursively if needed), but on the top level at least, I'd advice for using named exports. The other advantages are: Better support in build tools because they can statically analyze exports, and modules can only import what they need. – Felix Kling Aug 28 '18 at 16:20
1
export default {
foo: 'foo',
bar: 'bar'
}

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

Then 
const.foo
Ravi Rane
  • 159
  • 1
  • 1
    Can you provide some explanation, it will be good for understanding – Sinto Aug 28 '18 at 05:25
  • if you use * sign it try to import every things and put in an object to handle imported things. with this approach you do not need to use * and there is no need to an extra object to handle imported things. so you can use const.foo instead of constants.default.foo – mustafa kemal tuna Feb 15 '21 at 16:50