Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these ES6 import methods? [duplicate]

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/

like image 212
Don P Avatar asked Dec 08 '15 17:12

Don P


2 Answers

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

like image 198
Brandon Avatar answered Oct 25 '22 07:10

Brandon


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
like image 1
Sterling Archer Avatar answered Oct 25 '22 07:10

Sterling Archer