6

What is the difference between these import methods?

Method 1:

import {sum, pi} from "lib/math";

Method 2:

import exp, {pi, e} from "lib/mathplusplus";

The es2015 docs showed these two examples, and I can't figure out the purpose of the curly braces. It seems like all of the things listed after import will be assigned to the window object anyway.

Docs for reference: https://babeljs.io/docs/learn-es2015/

Don P
  • 60,113
  • 114
  • 300
  • 432
  • The first imports named exports `sum` and `pi`. The second imports the default export as `exp`, and also named exports `pi` and `e`. –  Dec 08 '15 at 17:43
  • In case you're interested in learning more about the differences, an excellent resource is the following: https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20&%20beyond/ch3.md#modules – wmock Dec 08 '15 at 18:05

3 Answers3

13

modules can export multiple things. Modules can also have a single "default" export.

import exp from "somelib";

This assigns the default export of somelib to the variable exp.

import {a, b} from "somelib";

This assigns the non-default named exports a and b to local variables a and b.

import exp, {a, b} from "somelib";

Assigns the default export to exp and the named exports to a and b.

import * as somelib from "somelib";

Takes all of the named exports of somelib and assigns them as an object to the local variable somelib, which means you will have somelib.a, somelib.b, etc.

This is a very good resource for the topic: http://www.2ality.com/2014/09/es6-modules-final.html

Brandon
  • 38,310
  • 8
  • 82
  • 87
1

In this case, exp is the default module to be imported, named exp. pi and e are wrapped in curly braces because they are not defaulted.

In this example, you defined a default module:

export default function(x) {
  return x + x;
}

And import is without curly braces, naming it whatever you want:

import double from 'mymodule';
double(2); // 4
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
1

Modules can export in two different ways. They can use default, or just perform a standard export

export default function exp(value, power) {}
export const pi = 3.14159

When you import from a module you need to use the curly braces to capture non-default exports. If you want the default export, you don't need the braces.

import exp, {pi} from "lib/mathplusplus";
Kyeotic
  • 19,697
  • 10
  • 71
  • 128