This question already has an answer here:
- When should I use brackets with imports 2 answers
I do not understand the difference between "import {Something} from somelib" and "import Something from somelib" in React.js. Could someone, please, explain it?
It totally depends on how the library is exporting objects / functions.
See the following cases:
Consider a library which exports this way:
When importing from above library:
Syntax 1
To import
func1
we would writeSyntax 2
To import
func2
/func3
,Now, if you do
Syntax 3
You would get
x = { func2, func3, default: { func1 } }
A library without default export:
Import Syntaxes:
Syntax 1
If we write
Syntax 2
To import
func2
/func3
,Syntax 3
To import all,
You would get
x = { func2, func3, func1 }
Now consider a library which uses
module.exports
When importing
Now consider another library:
Now to import
func1
you would do:So, if you wish to import the complete library (or its default export) you would use
import x from 'lib';
If the library exports an object and you only want some keys of that object, you would use
import {key} from 'lib';
If you want all the keys as another object x, you would use
import * as x from 'lib';
There is a huge difference though :)
import {Something} from somelib -> import specific export "Something" from the library
import Something from somelib -> import only default export and give the alias name as Somthing.
When working with ES6 modules, you have two types of exports:
The difference between these is how you import them. If you have a single file with multiple modules, it makes sense to give each module a name and be able to import each of them individually, without having to import the entire contents of the file.
For example, say you have 3 modules in one file, and you export them as
export A; export B; export C;
. You can then import any one of them using the curly brackets import syntax. Soimport {A, B}
, for example will import module A and B only.The default export syntax is commonly used in React when you want to export a component, and nothing else from a file. By exporting something with
export default A
, you can import that module by using theimport X from ../file
, where X is an alias and can be anything (but usually the same name is used for consistency).You can read more about ES6 import & export here and here.