2

In a file called index.js i have the following export:

export default {
  foo: true,
  bar: false
}

Later in file home.js i'm doing the following:

import { foo, bar } from './index'

console.log(foo, bar) -> undefined, undefined

If i import everything like:

import index from './index'

console.log(index) -> { foo: true, bar: false }

Can someone explain me why this is happening? I'm doing something wrong?

I'm using:

› create-react-app -V 1.0.3

Anderson
  • 331
  • 1
  • 4
  • 18
  • this is how it should work as specified in ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import – Davin Tryon Jan 13 '17 at 17:13
  • Related: [ES6 Destructuring and Module imports](http://stackoverflow.com/q/33524696/218196), [When should I use curly braces for ES6 import?](http://stackoverflow.com/q/36795819/218196) – Felix Kling Jan 13 '17 at 17:47

1 Answers1

3

What you have there are named exports, not destructuring.

You have to export them as such, not as a default export:

// this will export all of the defined properties as individual
// named exports, which you can pick-and-choose when importing
// using a similar syntax to destructuring
const foo = true, bar = false;
export {
  foo,
  bar
}

// imported exports named 'foo' and 'bar'
import { foo, bar } from './my-file'.

If you specify a default export, then whatever follows the keyword default will be exported when you import without curly braces:

// this exports an object containing { foo, bar } as the default export
export default {
  foo: true,
  bar: false
}

// imported without {}
import objectContainingFooBar from './my-file';
nem035
  • 34,790
  • 6
  • 87
  • 99