ES6 中的“export const"与“export default" [英] `export const` vs. `export default` in ES6
问题描述
我正在尝试确定这两者之间是否有任何大的区别,除了能够使用 export default
导入之外,只需执行以下操作:
I am trying to determine if there are any big differences between these two, other than being able to import with export default
by just doing:
import myItem from 'myItem';
并且使用 export const
我可以做到:
And using export const
I can do:
import { myItem } from 'myItem';
除此之外还有其他区别和/或用例吗?
Are there any differences and/or use cases other than this?
推荐答案
这是命名导出与默认导出.export const
是一个命名的导出,它导出一个或多个 const 声明.
It's a named export vs a default export. export const
is a named export that exports a const declaration or declarations.
要强调的是:这里重要的是export
关键字为 const
用于声明一个或多个 const 声明.export
也可以应用于其他声明,例如类或函数声明.
To emphasize: what matters here is the export
keyword as const
is used to declare a const declaration or declarations. export
may also be applied to other declarations such as class or function declarations.
默认导出(export default
)
每个文件可以有一个默认导出.导入时,您必须指定名称并像这样导入:
You can have one default export per file. When you import you have to specify a name and import like so:
import MyDefaultExport from "./MyFileWithADefaultExport";
你可以给它任何你喜欢的名字.
You can give this any name you like.
命名导出(export
)
使用命名导出,每个文件可以有多个命名导出.然后导入你想要用大括号括起来的特定导出:
With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:
// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";
// use MyClass, MyOtherClass, and MyClass2Alias here
或者可以在同一个语句中使用默认值和命名导入:
Or it's possible to use a default along with named imports in the same statement:
import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";
命名空间导入
也可以从文件中导入对象上的所有内容:
It's also possible to import everything from the file on an object:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here
注意事项
- 语法倾向于默认导出稍微简洁一点,因为它们的用例更常见(请参阅此处的讨论).
默认导出实际上是名称为
default
的命名导出,因此您可以使用命名导入来导入它:
- The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).
A default export is actually a named export with the name
default
so you are able to import it with a named import:
import { default as MyDefaultExport } from "./MyFileWithADefaultExport";
这篇关于ES6 中的“export const"与“export default"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!