Javascript(ES6),export const vs export default [英] Javascript (ES6), export const vs export default

查看:551
本文介绍了Javascript(ES6),export const vs export default的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定这两个之间是否存在很大差异,除了可以通过 export default 导入之外,只需执行以下操作:

I am trying to determine if there is any big differences between these 2, 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 with the const keyword.

默认导出(导出默认值

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.

命名导出(导出

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 import all the named exports onto an object:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClass.MyOtherClass here

您可以使用默认导出或同时命名为export或both。这种语法有利于默认出口,因为它们的用例更为常见(请参阅这里的讨论)。

You can use a default export or named exports or both at the same time. The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).

请注意,默认导出实际上是名为默认的命名导出,因此您可以将其导入做:

Note that a default export is actually a named export with the name default so you are able to import it by doing:

import {default as MyDefaultExport} from "./MyFileWithADefaultExport";

这篇关于Javascript(ES6),export const vs export default的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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