Javascript 什么时候应该使用花括号进行 ES6 导入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36795819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:33:53  来源:igfitidea点击:

When should I use curly braces for ES6 import?

javascriptimportecmascript-6

提问by TonyGW

It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content:

这似乎很明显,但我发现自己对何时使用花括号在 ES6 中导入单个模块感到有些困惑。例如,在我正在处理的 React-Native 项目中,我有以下文件及其内容:

初始状态.js
var initialState = {
    todo: {
        todos: [
            {id: 1, task: 'Finish Coding', completed: false},
            {id: 2, task: 'Do Laundry', completed: false},
            {id: 2, task: 'Shopping Groceries', completed: false},
        ]
    }
};

export default initialState;

In the TodoReducer.js, I have to import it without curly braces:

在 TodoReducer.js 中,我必须在没有花括号的情况下导入它:

import initialState from './todoInitialState';

If I enclose the initialStatein curly braces, I get the following error for the following line of code:

如果我将 括initialState在花括号中,则会收到以下代码行的以下错误:

Cannot read property todo of undefined

无法读取未定义的属性待办事项

TodoReducer.js:
export default function todos(state = initialState.todo, action) {
// ...
}

Similar errors also happen to my components with the curly braces. I was wondering when I should use curly braces for a single import, because obviously, when importing multiple component/modules, you have to enclose them in curly braces, which I know.

类似的错误也发生在我的带花括号的组件上。我想知道什么时候应该对单个导入使用花括号,因为显然,当导入多个组件/模块时,您必须将它们括在花括号中,我知道这一点。

Edit:

编辑:

The SO post at heredoes not answer my question, instead I am asking whenI should or should not use curly braces for importing a singlemodule, or I should never use curly braces for importing a single module in ES6 (this is apparently not the case, as I have seen single import with curly braces required)

此处的 SO 帖子没有回答我的问题,而是问我何时应该或不应该使用花括号导入单个模块,或者我永远不应该使用花括号导入 ES6 中的单个模块(这显然不是案例,因为我已经看到需要花括号的单个导入)

回答by Dan Abramov

This is a default import:

这是默认导入

// B.js
import A from './A'

It only works if Ahas the default export:

它仅在A具有默认导出时才有效:

// A.js
export default 42

In this case it doesn't matter what name you assign to it when importing:

在这种情况下,导入时分配给它的名称并不重要:

// B.js
import A from './A'
import MyA from './A'
import Something from './A'

Because it will always resolve to whatever is the default exportof A.

因为它会始终解析到任何的是默认的导出A



This is a named import called A:

这是一个名为的命名导入A

import { A } from './A'

It only works if Acontains a named export called A:

它仅在A包含名为 的命名导出A时才有效:

export const A = 42

In this case the name matters because you're importing a specific thing by its export name:

在这种情况下,名称很重要,因为您要通过其导出名称导入特定事物

// B.js
import { A } from './A'
import { myA } from './A' // Doesn't work!
import { Something } from './A' // Doesn't work!

To make these work, you would add a corresponding named exportto A:

为了使这些工作,你需要添加一个相应的命名导出A

// A.js
export const A = 42
export const myA = 43
export const Something = 44


A module can only have one default export, but as many named exports as you'd like(zero, one, two, or many). You can import them all together:

一个模块只能有一个默认的 export,但可以有任意数量的命名导出(零、一、二或多)。您可以将它们全部导入:

// B.js
import A, { myA, Something } from './A'

Here, we import the default export as A, and named exports called myAand Something, respectively.

在这里,我们将默认导出导入为A,命名导出分别称为myASomething

// A.js
export default 42
export const myA = 43
export const Something = 44

We can also assign them all different names when importing:

我们还可以在导入时为它们分配不同的名称:

// B.js
import X, { myA as myX, Something as XSomething } from './A'


The default exports tend to be used for whatever you normally expect to get from the module. The named exports tend to be used for utilities that might be handy, but aren't always necessary. However it is up to you to choose how to export things: for example, a module might have no default export at all.

默认导出往往用于您通常期望从模块中获得的任何内容。命名导出往往用于可能很方便但并不总是必要的实用程序。但是,您可以选择如何导出内容:例如,模块可能根本没有默认导出。

This is a great guide to ES modules, explaining the difference between default and named exports.

这是一个很好的 ES 模块指南,解释了默认导出和命名导出之间的区别。

回答by Daniel Schmidt

TL;DR: Curly braces are used if you would like to import a non-default export.

TL;DR:如果您想导入非默认导出,请使用花括号。

See Dan Abramovs answer above for more details.

有关更多详细信息,请参阅上面的 Dan Abramovs 回答。

回答by prosti

I would say there is also a starred notation for the importES6 keyword worth to mention.

我想说还有一个import值得一提的ES6 关键字的星号符号。

enter image description here

enter image description here

If you try to console log Mix:

如果您尝试控制台日志 Mix:

import * as Mix from "./A";
console.log(Mix);

You will get:

你会得到:

enter image description here

enter image description here

When should I use curly braces for ES6 import?

什么时候应该使用花括号进行 ES6 导入?

The brackets are golden when you need only specific components from the module, which makes smaller footprints for bundlers like webpack.

当您只需要模块中的特定组件时,括号是金色的,这使得像 webpack 这样的打包器占用的空间更小。

回答by Deepak Sharma

Dan Abramov answer above explains about the default exportsand named exports.

Dan Abramov 上面的回答解释了默认的导出命名的导出

Which to use?

使用哪个?

Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

引用 David Herman 的话:ECMAScript 6 支持单一/默认导出样式,并为导入默认提供了最甜蜜的语法。导入命名导出可以甚至应该稍微不那么简洁。

However in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references. Named exports is also preferred for utilities.

然而,在 TypeScript 中命名导出由于重构而受到青睐。例如,如果您默认导出一个类并对其重命名,则类名只会在该文件中更改,而不会在其他引用中更改,命名导出类名将在所有引用中重命名。命名导出也是实用程序的首选。

Overall use whatever you prefer.

总体使用您喜欢的任何内容。

Additional

额外的

Default export is actually a named export with name default, so default export can be imported as:

默认导出实际上是名称为 default 的命名导出,因此默认导出可以导入为:

import {default as Sample} from '../Sample.js';

回答by Brandon

If you think of importas just syntax sugar for node modules, objects, and destructuring, I find it's pretty intuitive.

如果您认为import只是节点模块、对象和解构的语法糖,我会发现它非常直观。

// bar.js
module = {};

module.exports = { 
  functionA: () => {},
  functionB: ()=> {}
};

 // really all that is is this:
 var module = { 
   exports: {
      functionA, functionB
   }
  };

// then, over in foo.js

// the whole exported object: 
var fump = require('./bar.js'); //= { functionA, functionB }
// or
import fump from './bar' // same thing, object functionA and functionB props


// just one prop of the object
var fump = require('./bar.js').functionA;

// same as this, right?
var fump = { functionA, functionB }.functionA;

// and if we use es6 destructuring: 
var { functionA } =  { functionA, functionB };
// we get same result

// so, in import syntax:
import { functionA } from './bar';

回答by theTypan

In order to understand the use of curly braces in importstatements, first, you have to understand the concept of destructingintroduced in ES6

为了理解大括号在import语句中的使用,首先要理解ES6中引入的析构概念

  1. Object destructuring

    var bodyBuilder = {
      firstname: 'Kai',
      lastname: 'Greene',
      nickname: 'The Predator'
    };
    
    var {firstname, lastname} = bodyBuilder;
    console.log(firstname, lastname); //Kai Greene
    
    firstname = 'Morgan';
    lastname = 'Aste';
    
    console.log(firstname, lastname); // Morgan Aste
    
  2. Array destructuring

    var [firstGame] = ['Gran Turismo', 'Burnout', 'GTA'];
    
    console.log(firstGame); // Gran Turismo
    

    Using list matching

      var [,secondGame] = ['Gran Turismo', 'Burnout', 'GTA'];
      console.log(secondGame); // Burnout
    

    Using the spread operator

    var [firstGame, ...rest] = ['Gran Turismo', 'Burnout', 'GTA'];
    console.log(firstGame);// Gran Turismo
    console.log(rest);// ['Burnout', 'GTA'];
    
  1. 对象解构

    var bodyBuilder = {
      firstname: 'Kai',
      lastname: 'Greene',
      nickname: 'The Predator'
    };
    
    var {firstname, lastname} = bodyBuilder;
    console.log(firstname, lastname); //Kai Greene
    
    firstname = 'Morgan';
    lastname = 'Aste';
    
    console.log(firstname, lastname); // Morgan Aste
    
  2. 数组解构

    var [firstGame] = ['Gran Turismo', 'Burnout', 'GTA'];
    
    console.log(firstGame); // Gran Turismo
    

    使用列表匹配

      var [,secondGame] = ['Gran Turismo', 'Burnout', 'GTA'];
      console.log(secondGame); // Burnout
    

    使用扩展运算符

    var [firstGame, ...rest] = ['Gran Turismo', 'Burnout', 'GTA'];
    console.log(firstGame);// Gran Turismo
    console.log(rest);// ['Burnout', 'GTA'];
    

Now that we've got that out of our way, in ES6you can export multiple modules. You can then make use of object destructuring like below

现在我们已经解决了这个问题,在ES6 中你可以导出多个模块。然后,您可以使用如下所示的对象解构

Let's assume you have a module called module.js

假设您有一个名为的模块 module.js

    export const printFirstname(firstname) => console.log(firstname);
    export const printLastname(lastname) => console.log(lastname);

You would like to import the exported functions into index.js;

您想将导出的函数导入到index.js;

    import {printFirstname, printLastname} from './module.js'

    printFirstname('Taylor');
    printLastname('Swift');

You can also use different variable names like so

你也可以像这样使用不同的变量名

    import {printFirstname as pFname, printLastname as pLname} from './module.js'

    pFname('Taylor');
    pLanme('Swift');

回答by Willem van der Veen

Summary ES6modules:

总结ES6模块:

exports:

出口:

You have 2 types of exports:

您有两种类型的导出:

  1. Named exports
  2. Default exports, Max 1 per module
  1. 命名导出
  2. 默认导出,每个模块最多 1 个

Syntax:

句法:

// Module A
export const importantData_1 = 1;
export const importantData_2 = 2;
export default function foo () {}


Imports:

进口:

The type of export(i.e. named or default exports) affects how to import something:

导出类型(即命名或默认导出)会影响如何导入:

  1. For a named export we have to use curly braces and the exact nameas the declaration (i.e. variable, function, or class) which was exported.
  2. For a default export we can choose the name.
  1. 对于命名导出,我们必须使用大括号和确切名称作为导出的声明(即变量、函数或类)。
  2. 对于默认导出,我们可以选择名称。

Syntax:

句法:

// Module B, imports from module A which is located in the same directory

import { importantData_1 , importantData_2  } from './A';  // for our named imports

// syntax single named import: 
// import { importantData_1 } 

// for our default export (foo), the name choice is arbitrary
import ourFunction from './A';   

Things of interest:

感兴趣的东西:

  1. Use a comma separated list within curly braces with the matching nameof the export for named export.
  2. Use a name of your choosing without curly braces for a default export.
  1. 使用花括号内的逗号分隔列表和命名导出的导出名称匹配
  2. 使用您选择的不带花括号的名称作为默认导出。

Aliases:

别名:

Whenever you want to rename a named import this is possible via aliases. The syntax for this is the following:

每当您想重命名命名导入时,这都可以通过aliases。其语法如下:

import { importantData_1 as myData } from './A';

Now we have imported importantData_1but the identifier is myDatainstead of importantData_1.

现在我们已经导入,importantData_1但标识符myData不是importantData_1.

回答by jadlmir

usually when you export a function you need to use the {}

通常当您导出函数时,您需要使用 {}

if you have export const x 

you use import {x} from ''

你用 import {x} from ''

if you use export default const x 

you need to use import X from ''here you can change X to whatever variable you want

您需要在import X from ''这里使用您可以将 X 更改为您想要的任何变量

回答by samuelj90

The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment

花括号 ({}) 用于导入命名绑定,其背后的概念是解构赋值

A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?

可以在我自己对类似问题的回答中找到有关 import 语句如何与示例一起工作的简单演示,我们何时在 javascript 导入中使用 '{ }'?

回答by Abhishek Kumar

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.

花括号仅在命名导出时用于导入。如果导出是默认的,那么大括号不用于导入。