我什么时候应该在导入中使用括号 [英] When should I use brackets with imports

查看:45
本文介绍了我什么时候应该在导入中使用括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,第一个是todoHelper.js

I have two file, the first one is todoHelper.js

它有 export const addTodo = (list, item) =>[...列表,项目]

稍后我想在另一个文件中使用 addTodo,我只需执行 import {addTodo} from './todoHelpers'

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

但我也看到人们在进行默认导出,而不仅仅是导出.有什么区别?

But I'm also seeing people doing export default instead of just export. What's the differences?

推荐答案

每个文件只能有一个导出默认值,因此当你像

You can have only one export default per file and hence when you do export default like

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

你可以像这样导入

import MyAddTodo from './todoHelpers'

由于 babel 知道您正在尝试访问默认组件,因此您可以在文件中通过任何名称访问它

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

现在假设你这样做

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

你可以在你的文件中有多个这样的导出

You can have multiple such exports in you file like

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

当你导入时,你需要像

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

现在,由于您有多个这样的导出,因此如果您使用不同的名称(如

Now since you have multiple such exports thus babel wont know which component you are tyring to access if you access if by a different name like

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

如果你想这样做,你必须按原样导入它们,然后它们会改变它们的名字

If you want to do this you will have to import them as it is and them change thier name like

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

因此,作为一般做法,您将默认导出主要组件,其余部分可以正常导出,或者当您只有一个组件需要从文件导出时,您可以选择任何内容你想要但一个很好的方法是将它export 作为默认值.

So as general practice you will default export the main component and the rest you can have as export normally or when you have only one component that you need to export from a file then you can choose whatever you want but a nice way will be to export it as default.

这篇关于我什么时候应该在导入中使用括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆