When do we use '{ }' in javascript imports? [duplicate] - javascript

This question already has answers here:
When should I use curly braces for ES6 import?
(11 answers)
Closed 4 years ago.
I am learning Javascript imports and I am yet to understand when we use curly braces while importing items(functions, objects, variables) from another JS file.
import Search from './models/Search';
import * as searchView from './views/searchView';
import { elements, renderLoader } from './views/base'
//elements is an object, renderLoader is a function

The import statements are used to import the exported bindings from another module
The curly braces ({}) are used to import named bindings and the concept behind it is called destructuring assignment The concept of destructuring assignment is a process that makes it possible to unpack the values from arrays or objects into distinct variables in the imported module
The curly braces ({}) are used to import named bindings
I would like to explain different types of imports in ES6 with the help of an example
Suppose we have a module named Animals(Animals.js) let suppose the module exports a default binding Man and several other named bindings such as Cat, Dog etc
/*
Animals.js
*/
..
export Cat;
export Dog
export default Man
Import a single export from a module
In order to export a single export from another module (let's say Cat) we can write it like this
/*
Anothermodule.js
*/
import {Cat} from "./Animals"
Similarly for Dog
/*
YetAnothermodule.js
*/
import {Dog} from "./Animals"
Import multiple exports from module
You can also import multiple modules as follows
/*
Anothermodule.js
*/
import {Dog, Cat} from "./Animals"
Import an export with a more convenient alias
/*
Anothermodule.js
*/
import {Dog as Puppy} from './Animals.js';
Rename multiple exports during import
/*
Anothermodule.js
*/
import {Dog as Puppy, Cat as Kitty} from './Animals.js';
But in the case to import Man into another module since it is a default export you can write it like this
/*
Anothermodule.js
*/
import Man from './Animals.js';
You can also mix both the above variants for example
/*
Anothermodule.js
*/
import Man, {Dog as Puppy, Cat as Kitty} from '/Animals.js';
Import an entire module's contents
If you want to import everything you can use
/*
Anothermodule.js
*/
import * as Animals from './Animals.js';
Here, accessing the exports means using the module name ("Animals" in this case) as a namespace. For example, if you want to use Cat in this case you can use it like below
Animals.Cat
You can read more information about import here
you can read about destructuring here

import { elements, renderLoader } from './views/base'
is the way you need to import single, named exports from a module, in this case it is importing named exports elements and renderLoader from base.js.
The { elements, renderLoader } syntax is in many cases just syntactic sugar (called destructuring) added in recent versions of the ECMAScript standard.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
In this case, though, it is necessary to get only the named exports you want.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_single_export_from_a_module
Please note that you can also pick new names for your variables like this:
import { elements as newNameForElements, renderLoader as newNameForRenderLoader } from './views/base'
which would then make the elements export available as newNameForElements etc.

import Search from './models/Search';
Imports the default exported element as Search.
import * as searchView from './views/searchView';
Imports everything into searchView that has been exported.
import { elements, renderLoader } from './views/base'
Imports a hand-picked number of named exported elements.

{} is used when you want to import part of an object. The * as searchView one will import all properties and methods in the searchView file.
Suppose './views/base' has 3 properties: elements, renderLoader, additionalParam (Assuming that all three have been exported as named exports in the file)
When doing
import { elements, renderLoader } from './views/base'
you import only those 2 specific properties
But when you do
import * as base from './views/base'
you import all three properties in the object named base

Take the following example:
File to be imported, say importedFile.js:
var defaultExport, otherExport1, otherExport2, otherExport3;
export default defaultExport = () => {
console.log("Default Export")
}
export otherExport1 = "Other non-default Export";
export otherExport2 = function() {
console.log("Some more non-default Export");
};
export otherExport3 = { msg: "again non-default Export" };
Now in your main JS file, if you would do the following:
import something from './importedFile.js;
Here the variable something would get the value of the variable/function that has been exported as default in the importedFile.js file, i.e. the variable defaultExport. Now, if you do something like the following:
import { otherExport1, otherExport2 } from './importedFile.js;
It would import specifically otherExport1 and otherExport2 variable and function and not the defaultExport and otherExport3.
You can also do something like the following to import all the variables by their names from importedFile.js:
import { defaultExport, otherExport1, otherExport2, otherExport3 } from './importedFile.js';
Conclusion:
curly braces are used to choose variables/functions/objects (using a technique called object destructuring in ES6) that need to be imported without importing all the other unnecessary exported variables/functions/objects.
If you don't specify curly braces, it would always import only the variable/function/object that has been exported as default and nothing else. It would import undefined if nothing has been exported as default export.

You can use curly braces to import implicitly and selectively from another module functions or objects and so on.
// import implicitly one function and one constant from example.js
import { a, b } from 'example'
example.js
// export a and b but kept c private to example.js
export const a => { ... }
export const b = "hello"
const c = "private, not visible to the outside"
More infos:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

If something is exported as default it is imported without curly braces.
If multiple variables are exported it is imported using curly braces.
For example,
in somefunction.js
export default module;
import module from './somefunction.js';
in someOtherFunction.js
export func1;
export func2;
import { func1, func2 } from './someOtherFunction.js'

You can export more than 1 content from a single module.
For example at your code:
import * as searchView from './views/searchView'; //1
import { elements, renderLoader } from './views/base' //2
At //1, you import Everything from './views/searchView';
At //2, there might be more content from './views/base', but you import only elements and renderLoader
For more information: import MDN

Related

What's difference between name and {name} in react? [duplicate]

I have referred all the questions in stackoverflow.
But none of the suggested why and when to use default export.
I just saw that default can be metioned "When there is only one export in a file"
Any other reason for using default export in es6 modules?
Some differences that might make you choose one over the other:
Named Exports
Can export multiple values
MUST use the exported name when importing
Default Exports
Export a single value
Can use any name when importing
This article does a nice job of explaining when it would be a good idea to use one over the other.
It's somewhat a matter of opinion, but there are some objective aspects to it:
You can have only one default export in a module, whereas you can have as many named exports as you like.
If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does
import example from "./example";
...but Joe does
import ex from "./example";
In contrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module.¹ It's just
import { example } from "./example";
With a named export, the person importing it has to specify the name of what they're importing. They get a nice early error if they try to import something that doesn't exist.
If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.
¹ If there is a conflict (for instance, you want example from two different modules), you can use as to rename:
import { example as widgetExample } from "./widget/example";
import { example as gadgetExample } from "./gadget/example";
You should almost always favour named exports, default exports have many downsides
Problems with default exports:
Difficult to refactor or ensure consistency since they can be named anything in the codebase other than what its actually called
Difficult to analyze by automated tools or provide code intellisense and autocompletion
They break tree shaking as instead of importing the single function you want to use you're forcing webpack to import the entire file with whatever other dead code it has leading to bigger bundle sizes
You can't export more than a single export per file
You lose faster/direct access to imports
checkout these articles for a more detailed explanation:
https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad
https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
https://rajeshnaroth.medium.com/avoid-es6-default-exports-a24142978a7a
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
You can also alias named imports, assign a new name to a named export as you import it, allowing you to resolve naming collisions, or give the export a more informative name.
import MyComponent as MainComponent from "./MyComponent";
You can also Import all the named exports onto an object:
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
The naming of import is completely independent in default export and we can use any name we like.
From MDN:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.
There aren't any definitive rules, but there are some conventions that people use to make it easier to structure or share code.
When there is only one export in the entire file, there is no reason to make it named.
Also, when your module has one main purpose, it could make sense to make that your default export. In those cases you can extra named exports
In react for example, React is the default export, since that is often the only part that you need. You don't always Component, so that's a named export that you can import when needed.
import React, {Component} from 'react';
In the other cases where one module has multiple equal (or mostly equal) exports, it's better to use named exports
import { blue, red, green } from 'colors';
1st Method:-
export foo; //so that this can be used in other file
import {foo} from 'abc'; //importing data/fun from module
2nd Method:-
export default foo; //used in one file
import foo from 'blah'; //importing data/fun from module
3rd Method:-
export = foo;
import * as foo from 'blah';
The above methods roughly compile to the following syntax below:-
//all export methods
exports.foo = foo; //1st method
exports['default'] = foo; //2nd method
module.exports = foo; //3rd method
//all import methods
var foo = require('abc').foo; //1st method
var foo = require('abc')['default']; //2nd method
var foo = require('abc'); //3rd method
For more information, visit to Default keyword explaination
Note:- There can be only one export default in one file.
So whenever we are exporting only 1 function, then it's better to use default keyword while exporting
EASIEST DEFINITION TO CLEAR CONFUSIONS
Let us understand the export methods, first, so that we can analyze ourselves when to use what, or why do we do what we do.
Named exports: One or more exports per module. When there are more than one exports in a module, each named export must be restructured while importing. Since there could be either export in the same module and the compiler will not know which one is required unless we mention it.
//Named export , exporting:
export const xyz = () =>{
}
// while importing this
import {xyx} from 'path'
or
const {xyz} = require(path)
The braces are just restructuring the export object.
On the other hand , default exports are only one export per module , so they are pretty plain.
//exporting default
const xyz =() >{
};
export default xyz
//Importing
import xyz from 'path'
or
const xyz = require(path)
I hope this was pretty simple to understand, and by now you can understand why you import React modules within braces...
Named Export: (export)
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
Import all the named exports onto an object:
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
import * as MainComponents from "./MyComponent";
Default Export: (export default)
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
Note: The naming of import is completely independent in default export and we can use any name we like.
Here's a great answer that explains default and named imports in ES6

Why do we have to use “*” while importing in typescript? [duplicate]

What is the difference in TypeScript between export and default export?
In all the tutorials, I see people exporting their classes and I cannot compile my code if I don't add the default keyword before exporting.
Also, I couldn't find any trace of the default export keyword in the official TypeScript documentation.
export class MyClass {
collection = [1,2,3];
}
Does not compile. But:
export default class MyClass {
collection = [1,2,3];
}
Does.
The error is:
error TS1192: Module '"src/app/MyClass"' has no default export.
Default Export (export default)
// MyClass.ts -- using default export
export default class MyClass { /* ... */ }
The main difference is that you can only have one default export per file and you import it like so:
import MyClass from "./MyClass";
You can give it any name you like. For example this works fine:
import MyClassAlias from "./MyClass";
Named Export (export)
// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }
When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:
import { MyClass } from "./MyClass";
Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.
Or say your file exported multiple classes, then you could import both like so:
import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass
Or you could give either of them a different name in this file:
import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias
Or you could import everything that's exported by using * as:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here
Which to use?
In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.
Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.
That said, find what you prefer! You could use one, the other, or both at the same time.
Additional Points
A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:
import { default as MyClass } from "./MyClass";
And take note these other ways to import exist:
import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo'; in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo' in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in Avoid Export Default
Named export
In TypeScript you can export with the export keyword. It then can be imported via import {name} from "./mydir";. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same directory
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import, export, and export default are JavaScript constructs, not TypeScript. However, TypeScript added the exporting and importing of interfaces and type aliases to it.
Here's an example with simple object exporting.
var MyScreen = {
/* ... */
width : function (percent){
return window.innerWidth / 100 * percent
}
height : function (percent){
return window.innerHeight / 100 * percent
}
};
export default MyScreen
In the main file (use it when you don't want and don't need to create a new instance) and it is not global, you will import this only when it is needed:
import MyScreen from "./module/screen";
console.log(MyScreen.width(100));

Why and when to use default export over named exports in es6 Modules?

I have referred all the questions in stackoverflow.
But none of the suggested why and when to use default export.
I just saw that default can be metioned "When there is only one export in a file"
Any other reason for using default export in es6 modules?
Some differences that might make you choose one over the other:
Named Exports
Can export multiple values
MUST use the exported name when importing
Default Exports
Export a single value
Can use any name when importing
This article does a nice job of explaining when it would be a good idea to use one over the other.
It's somewhat a matter of opinion, but there are some objective aspects to it:
You can have only one default export in a module, whereas you can have as many named exports as you like.
If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does
import example from "./example";
...but Joe does
import ex from "./example";
In contrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module.¹ It's just
import { example } from "./example";
With a named export, the person importing it has to specify the name of what they're importing. They get a nice early error if they try to import something that doesn't exist.
If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.
¹ If there is a conflict (for instance, you want example from two different modules), you can use as to rename:
import { example as widgetExample } from "./widget/example";
import { example as gadgetExample } from "./gadget/example";
You should almost always favour named exports, default exports have many downsides
Problems with default exports:
Difficult to refactor or ensure consistency since they can be named anything in the codebase other than what its actually called
Difficult to analyze by automated tools or provide code intellisense and autocompletion
They break tree shaking as instead of importing the single function you want to use you're forcing webpack to import the entire file with whatever other dead code it has leading to bigger bundle sizes
You can't export more than a single export per file
You lose faster/direct access to imports
checkout these articles for a more detailed explanation:
https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad
https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
https://rajeshnaroth.medium.com/avoid-es6-default-exports-a24142978a7a
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
You can also alias named imports, assign a new name to a named export as you import it, allowing you to resolve naming collisions, or give the export a more informative name.
import MyComponent as MainComponent from "./MyComponent";
You can also Import all the named exports onto an object:
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
The naming of import is completely independent in default export and we can use any name we like.
From MDN:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.
There aren't any definitive rules, but there are some conventions that people use to make it easier to structure or share code.
When there is only one export in the entire file, there is no reason to make it named.
Also, when your module has one main purpose, it could make sense to make that your default export. In those cases you can extra named exports
In react for example, React is the default export, since that is often the only part that you need. You don't always Component, so that's a named export that you can import when needed.
import React, {Component} from 'react';
In the other cases where one module has multiple equal (or mostly equal) exports, it's better to use named exports
import { blue, red, green } from 'colors';
1st Method:-
export foo; //so that this can be used in other file
import {foo} from 'abc'; //importing data/fun from module
2nd Method:-
export default foo; //used in one file
import foo from 'blah'; //importing data/fun from module
3rd Method:-
export = foo;
import * as foo from 'blah';
The above methods roughly compile to the following syntax below:-
//all export methods
exports.foo = foo; //1st method
exports['default'] = foo; //2nd method
module.exports = foo; //3rd method
//all import methods
var foo = require('abc').foo; //1st method
var foo = require('abc')['default']; //2nd method
var foo = require('abc'); //3rd method
For more information, visit to Default keyword explaination
Note:- There can be only one export default in one file.
So whenever we are exporting only 1 function, then it's better to use default keyword while exporting
EASIEST DEFINITION TO CLEAR CONFUSIONS
Let us understand the export methods, first, so that we can analyze ourselves when to use what, or why do we do what we do.
Named exports: One or more exports per module. When there are more than one exports in a module, each named export must be restructured while importing. Since there could be either export in the same module and the compiler will not know which one is required unless we mention it.
//Named export , exporting:
export const xyz = () =>{
}
// while importing this
import {xyx} from 'path'
or
const {xyz} = require(path)
The braces are just restructuring the export object.
On the other hand , default exports are only one export per module , so they are pretty plain.
//exporting default
const xyz =() >{
};
export default xyz
//Importing
import xyz from 'path'
or
const xyz = require(path)
I hope this was pretty simple to understand, and by now you can understand why you import React modules within braces...
Named Export: (export)
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
Import all the named exports onto an object:
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
import * as MainComponents from "./MyComponent";
Default Export: (export default)
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";
// export
const MyComponent = () => {}
export default MyComponent;
Note: The naming of import is completely independent in default export and we can use any name we like.
Here's a great answer that explains default and named imports in ES6

Re-exporting modules does not work with object spread

i have an index.js file that reads:
import aReducer from './ducks/a';
import bReducer from './ducks/b';
import * as aSelectors from './ducks/a';
import * as bSelectors from './ducks/b';
console.log(aReducer) //function i expect
console.log(aSelectors) //object with keys to selectors i expect
export { aReducer, bReducer, ...aSelectors, ...bSelectors };
If I console.log in this file I see that the reducers are functions I expect and the selectors alias are objects with keys to the selectors I expect. The reducers are default exports for the duck files and the selectors are exports from the same respective file.
However, when I try to import this module with another file I am only able to import the two reducers. The two selectors are undefined. I thought that de-structuring would add each key to my export object. What am I doing wrong?
other_file1.js
import { aReducer, bReducer } from 'my-module'; //works!
other_file2.js
import { someSelectorThatWasInMyaSelectorsObject } from 'my-module'; //does NOT work!
You cannot use ... in an export {}; block. It is an explicit list of names just like import {name} from is. It is not an object with keys being exported. e.g. the same way imports do
import { foo as fooRenamed } from "";
with export it is
export {
fooVar as foo,
};
The export block is an explicit list of variables to export, with an optional explicit name for the export. There are no objects involved.
Specifically, there are no objects involved because the names of the exports are processed and known before the body of the file has even executed, so not only are objects not allowed, they are impossible to allow because objects require execution to exist.
To get what you'd want, you should use:
// Export the referenced files' default under two specific names.
export { default as aReducer } from './ducks/a';
export { default as bReducer } from './ducks/b';
// Re-export every named export from these two files.
export * from './ducks/a';
export * from './ducks/b';

Why do I need to wrap some importings with figure brackets {} in ES6? [duplicate]

This question already has answers here:
`export const` vs. `export default` in ES6
(6 answers)
Closed 6 years ago.
I found a strange situation in ES6. For example, I'm using npm packages react and react-router. I want to import them to the file:
import React from "react";
import { browserHistory } from "react-router";
The strange situation is that I need to wrap browserHistory in figure brackets, but I don't need to wrap React. What is the reason?
import { React } from "react"; // React is undefined
import browserHistory from "react-router"; // browserHistory is undefined
What's the reason that I need to customize my import?
ES6 modules differentiate between two kinds of exports: default exports and other exports.
Every module can have at most one default export. A default export is kind of like the “main attraction” of a module. It’s supposed to be the one thing that you probably meant the module to have. All other exports fit into the other category.
So a module can have any number of exports (even zero), of which at most one can be a default export.
On the export side of the syntax, a default export is simply marked by adding a default after the export keyword:
// this is a normal export
export var foo = 'foo';
// this is a default export
var bar = 'bar';
export default bar;
On the import side of the syntax, this gets a it more complicated: Default exports are imported outside of curly braces. All other exports are imported inside curly braces.
import bar, { foo } from 'some-module';
This would import the default exported member of the module as bar and also import the (named) other export foo. Note that default exports do not have a fixed name: The original name of the member at export time does not matter. Instead, you give it some name when importing it. So you could also write this instead:
import baz, { foo } from 'some-module';
This would still import the same default export from the module, but give it a different name. Other imports however are required to have the correct name, since that’s what’s used to identify them. You can however give them a different name by using the as keyword.
There are a few more things to know when using the export and import statements. You should check MDN for a full description of them.
If the module you are importing has a default export, then you do not have to use the { } syntax to access the given export. Named (non-default) exports must be accessed via the { } syntax. A module can have a default export as well as many named exports.
An example of that would be React which is a default export, but the module also has a named export of Component. To import both of these exports the syntax: import React, { Component } from 'react' would be used.

Categories

Resources