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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With