ES6中的“导出常量"与“导出默认值" [英] `export const` vs. `export default` in ES6

查看:671
本文介绍了ES6中的“导出常量"与“导出默认值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定这两者之间是否存在较大差异,除了可以通过以下操作使用export default进行导入之外:

I am trying to determine if there is any big differences between these two, other than being able to import with export default by just doing:

import myItem from 'myItem';

然后使用export const我可以做到:

import { myItem } from 'myItem';

我想知道除此之外是否还有其他差异和/或用例.

I am wondering if there are 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.

要强调:这里重要的是 关键字作为 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)

Default Export (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)

Named Export (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的命名导出,因此您可以使用命名import导入它:

  • 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中的“导出常量"与“导出默认值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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