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

时间:2021-11-05 14:50:02

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中的单个模块时有点困惑。例如,在我正在处理的堆本地项目中,我有以下文件及其内容:

initialState.js:

initialState.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 initialState in curly braces, I get the following error for the following line of code:

如果我用花括号括起initialState,我就会得到以下代码行中的错误:

Cannot read property todo of undefined

无法读取未定义的属性

TodoReducer.js:

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 here does not answer my question, instead I am asking when I should or should not use curly braces for importing a single module, 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)

所以邮报在这里不回答我的问题,不是我问当我应该或不应该为导入单个模块使用花括号,或者我不应该使用花括号中导入一个模块ES6(这是显然不是这样的,因为我看到单一进口需要花括号)

7 个解决方案

#1


1211  

This is a default import:

这是默认导入:

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

It only works if A has 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 export of A.

因为它总是解析为A的默认导出。


This is a named import called A:

这是一个名为a的导入:

import { A } from './A'

It only works if A contains 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 export to 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:

一个模块只能有一个默认的导出,但是有许多指定的导出(0,1,2,或很多)。您可以将它们全部导入:

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

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

在这里,我们将默认导出导入为A,并分别将命名导出命名为myA和Something。

// 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模块的一个很好的指南,解释了默认导出和命名导出之间的区别。

#2


71  

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

如果要导入非默认导出,则使用花括号。

See Dan Abramovs answer above for more details.

详见以上丹·阿布拉莫夫的回答。

#3


38  

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

我想说的是,导入ES6关键字也有一个星型符号值得提及。

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

If you try to console log Mix:

如果你尝试控制台日志混合:

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

You will get:

你将得到:

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

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之类的绑定器提供了更小的足迹。

#4


27  

Dan Abramov answer above explains about the default exports and 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.

然而,在命名为export的打字稿中,由于重构而受到青睐。例如,如果您默认导出一个类并对其进行重命名,那么类名只会在该文件中更改,而不会在其他引用中更改,命名的export类名将在所有引用中重命名。指定的出口也是公用事业的首选。

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';

#5


8  

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

如果您认为导入只是节点模块、对象和析构函数的语法糖,那么我发现它非常直观。

// 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';

#6


0  

In order to understand the use of curly braces in import statements, first, you have to understand the concept of destructing introduced in ES6

为了理解在导入语句中使用花括号,首先,您必须理解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'];
    

Now that we've got that out of our way, in ES6 you 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

假设您有一个名为modu .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');

#7


0  

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

你需要使用导入X从这里你可以把X变成任何你想要的变量

#1


1211  

This is a default import:

这是默认导入:

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

It only works if A has 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 export of A.

因为它总是解析为A的默认导出。


This is a named import called A:

这是一个名为a的导入:

import { A } from './A'

It only works if A contains 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 export to 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:

一个模块只能有一个默认的导出,但是有许多指定的导出(0,1,2,或很多)。您可以将它们全部导入:

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

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

在这里,我们将默认导出导入为A,并分别将命名导出命名为myA和Something。

// 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模块的一个很好的指南,解释了默认导出和命名导出之间的区别。

#2


71  

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

如果要导入非默认导出,则使用花括号。

See Dan Abramovs answer above for more details.

详见以上丹·阿布拉莫夫的回答。

#3


38  

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

我想说的是,导入ES6关键字也有一个星型符号值得提及。

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

If you try to console log Mix:

如果你尝试控制台日志混合:

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

You will get:

你将得到:

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

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之类的绑定器提供了更小的足迹。

#4


27  

Dan Abramov answer above explains about the default exports and 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.

然而,在命名为export的打字稿中,由于重构而受到青睐。例如,如果您默认导出一个类并对其进行重命名,那么类名只会在该文件中更改,而不会在其他引用中更改,命名的export类名将在所有引用中重命名。指定的出口也是公用事业的首选。

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';

#5


8  

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

如果您认为导入只是节点模块、对象和析构函数的语法糖,那么我发现它非常直观。

// 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';

#6


0  

In order to understand the use of curly braces in import statements, first, you have to understand the concept of destructing introduced in ES6

为了理解在导入语句中使用花括号,首先,您必须理解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'];
    

Now that we've got that out of our way, in ES6 you 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

假设您有一个名为modu .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');

#7


0  

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

你需要使用导入X从这里你可以把X变成任何你想要的变量