23

Why does this work:

const str = 'stuff';
export {
  str
};

But not this:

export default {
  str: 'stuff'
};

I'd like to import it as the following:

import { str } from 'myLib';

I'd like to assign the value directly in the export and not require having to create a variable before hand.

Also when I try:

export {
  str: 'stuff'
};

I get the error:

SyntaxError: /home/karlm/dev/project/ex.js: Unexpected token, expected , (41:5)
  39 | 
  40 | export {
> 41 |   str: 'stuff'
     |      ^
  42 | };
  43 | 
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
basickarl
  • 37,187
  • 64
  • 214
  • 335
  • That is just how the export syntax works. It *looks* like object destructuring, which I guess is why you have expected to be able to export an *object*, but the two concepts are fundamentally different. Related reading: http://stackoverflow.com/questions/33524696/es6-destructuring-and-module-imports – CodingIntrigue Dec 22 '16 at 15:28
  • 1
    Kind of related: [ES6 Destructuring and Module imports](http://stackoverflow.com/q/33524696/218196) – Felix Kling Dec 22 '16 at 15:58
  • 1
    Also related: [Javascript (ES6), export const vs export default](http://stackoverflow.com/q/33611812/218196) – Felix Kling Dec 22 '16 at 16:00

2 Answers2

27

There are two styles of exports in ES6 -- named exports, and the default export. Named exports get exported with syntax like this:

export const str = 'stuff';
// or
const str = 'stuff';
export { str };

Default exports go like this:

const obj = { str: 'stuff' };
export default obj;
// or 
export default {
  str: 'stuff'
};

The difference shows up when you import. With the first, you need to include braces:

import { str } from 'myModule'; // 'stuff', from the first example

Without braces, it imports the default export:

import myModule from 'myModule'; //  {str: 'stuff'}, from the second example
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Scimonster
  • 32,893
  • 9
  • 77
  • 89
2

The main reason of the export statement is to be used to export functions, objects or primitives from a given file (or module).

But you need an identifier in order to be exported (so that it can be imported via import in another script).

You can simply do:

export const obj = {
  str: 'stuff'
};

During the import, you will be able to use the same name obj to refer to the corresponding value.

And import it like:

import { obj } from 'myLib';
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46