What is the difference between with and without curly bracket notation in export/import statements?

ecmascript-6, export, import, javascript

Solution

ES6 offers many ways to manage modules through import/export. But there are basically two main strategies:

- Default export/import with `export default` and `import module from './module'`

- Multiple exports/imports with `export` and `import {member} from './module'` or `import * as module from './module'`

(Mixing both is possible but not recommended.)

Module to export/import

function foo() {
  console.log('Foo');
}

function bar() {
  console.log('Bar');
}

Strategy #1: Default export/import

Export (module.js)

function foo() {
  console.log('Foo');
}

function bar() {
  console.log('Bar');
}

export default {foo, bar};

/*
  {foo, bar} is just an ES6 object literal that could be written like so:

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

  It is the legacy of the "Revealing Module pattern"...
*/

Import (main.js)

import module from './module';

module.foo(); // Foo
module.bar(); // Bar

Strategy #2: Multiple exports/imports

Export (module.js)

export function foo() {
  console.log('Foo');
}

export function bar() {
  console.log('Bar');
}

Import (main.js)

import {foo, bar} from './module';

foo(); // Foo
bar(); // Bar

/*
  This is valid too:

  import * as module from './module';

  module.foo(); // Foo
  module.bar(); // Bar
*/

As I said previously, ES6 modules are much more complex than that. For further information, I recommend you to read Exploring ES6 by Dr. Axel Rauschmayer, especially this chapter: http://exploringjs.com/es6/ch_modules.html.

Problem

I'm new to ES6 and a bit confused with the way classes are exported and imported. It seems many different notations are valid but work differently. I wrote a class like this in `src/web-api.js`: ``` class WebApi { // ... } export { WebApi }; ``` Which I import with: ``` import { WebApi } from './src/web-api.js' ``` This works fine, but before I've tried the same thing without curly brackets and it didn't work: ``` export WebApi; // Tells me '{' expected import WebApi from './src/web-api.js'; // No syntax error but WebApi is undefined ``` Even though on the MDN documentation for export, the notation `export expression;` appears to be valid. Likewise, this is how React is imported in my application file: ``` import React, { Component } from 'react'; ``` Why is one class with and another one without curly brackets? In general, how can I tell when to use and not to use curly brackets?

Original source

Related problems