This question already has an answer here:
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
in two different ways. They can usedefault
, or just perform a standardexport
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.In this case,
exp
is thedefault
module to be imported, namedexp
.pi
ande
are wrapped in curly braces because they are not defaulted.In this example, you defined a default module:
And import is without curly braces, naming it whatever you want:
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 variableexp
.import {a, b} from "somelib";
This assigns the non-default named exports
a
andb
to local variablesa
andb
.import exp, {a, b} from "somelib";
Assigns the default export to
exp
and the named exports toa
andb
.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 havesomelib.a
,somelib.b
, etc.This is a very good resource for the topic: http://www.2ality.com/2014/09/es6-modules-final.html