This question already has an answer here:
-
Javascript (ES6), export const vs export default
6 answers
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/
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
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
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";