Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between import {module} and import module [duplicate]

I have seen the following two variations for importing code from another module in ES6:

import {module}  from "./Module"

and

import module from "./Module"

where module is a ES6 class defined in the file

Module.js

What is the difference between the two import statements?

like image 392
user1934212 Avatar asked Oct 07 '17 09:10

user1934212


2 Answers

The difference is the way it is exported.

export default const myModule = {}

Basically it says "this is the default export". You import this with

import myModule from 'module'

The other way is that multiple entry points can be exported like this:

export const myModule1 = {}
export const myModule2 = {}

You import these with

import {myModule1, myModule2} from 'module'

and if both a default and named entry points are exported you can do this:

import myModule, {myModule1, myModule2} from 'module'

It does not seem completely logical, usually the package author should explain how their module should be imported. If you are the author, this will help you

like image 151
Mikkel Avatar answered Nov 05 '22 18:11

Mikkel


In the first case

import {module}  from "./Module"

you are importing single export from a module and inserts 'module' in the current scope. In Module.js file you have to have named exports:

export { module, module2 }; 

Please notice there are two named exports, but you are importing only one.

In second example you are importing default export:

import module from "./Module"

and in your Module.js file export can look like this:

export default module3;

Notice that you can import your default under different name.

like image 1
Andrzej Smyk Avatar answered Nov 05 '22 18:11

Andrzej Smyk