When to use parentheses with imports

I have two files, the first is todoHelper.js

it has export const addTodo = (list, item) => [...list, item]

later I want to use addTodo in another file, I just do import {addTodo} from './todoHelpers'

But I also see that people are export defaulting, not just exporting. What are the differences?

+5
source share
2 answers

You can have only one default export for each file, and therefore when exporting by default, for example

 export default AddTodo = (list, item) => [...list, item] 

You can import it as

 import MyAddTodo from './todoHelpers' 

Since babel knows that you are trying to access the component by default, you can access it in your file by any name

Now suppose you do

 export const AddTodo = (list, item) => [...list, item] 

You may have several such exports in your file, for example

export const AddTodo = (list, item) => [... list, item] export const DeleteTodo = (list, item) => [... list, item]

and when importing you will need to destroy them, for example

 import {AddTodo, DeleteTodo}from './todoHelpers' 

Now, since you have several such export data, babel does not know which component you are connecting to access if you access it using a different name, for example

 import {MyAddTodo, MyDeleteTodo}from './todoHelpers' 

If you want to do this, you will have to import them as is, and they change the name, for example

 import {AddTodo as MyAddTodo, DeleteTodo as MyDeleteTodo}from './todoHelpers' 

So, as a general practice, you will be the default export main component, and the rest you can have as an export in normal mode or when you have only one component that you need to export from a file, then you can select whatever you want, but beautifully will be export by default.

+7
source

Using the default keyword with export gives us the freedom to import with an alias

 export default k // in file my.js 

can be imported with the alias 'b'

 import b from 'my.js' 
0
source

Source: https://habr.com/ru/post/1263836/


All Articles