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

时间:2016-04-22 13:58:14

标签: javascript import ecmascript-6

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

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;

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

import initialState from './todoInitialState';

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

  

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

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

使用花括号的组件也会发生类似的错误。我想知道何时应该使用花括号进行单次导入,因为很明显,当导入多个组件/模块时,你必须将它们用花括号括起来,我知道。

编辑:

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

12 个答案:

答案 0 :(得分:1759)

这是默认导入

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

仅当A具有默认导出

时才有效
// A.js
export default 42

在这种情况下,导入时为其指定的名称无关紧要:

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

因为它始终会解析为A默认导出

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

import { A } from './A'

仅当A包含名为A 命名导出时才有效:

export const A = 42

在这种情况下,名称很重要,因为您要按其导出名称导入特定内容:

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

要使这些工作正常,您需要将对应的命名导出添加到A

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

一个模块只能有一个默认导出,但只需要(零,一,二或多个)。您可以将它们全部导入:

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

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

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

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

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

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

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

答案 1 :(得分:98)

TL; DR :如果您要导入非默认导出,则使用大括号。

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

答案 2 :(得分:64)

我想说还有一个值得提及的import ES6关键字的星号表示法。

enter image description here

如果您尝试控制日志Mix:

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

你会得到:

enter image description here

  

我应该何时使用大括号进行ES6导入?

当你只需要模块中的特定组件时,括号是金色的,这为webpack这样的捆绑包提供了更小的占用空间。

答案 3 :(得分:34)

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

使用哪种?

引用David Herman :ECMAScript 6支持单/默认导出样式,并提供最甜蜜的语法来导入默认值。导入命名导出可以,甚至应该略微简洁。

但是,由于重构,TypeScript中的命名导出很受欢迎。例如,如果默认导出类并重命名,则类名将仅在该文件中更改,而不会在其他引用中更改,并且将在所有引用中重命名已命名的exports类名。 实用程序也首选命名导出。

总体使用你喜欢的任何东西。

其他

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

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

答案 4 :(得分:13)

如果您认为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';

答案 5 :(得分:5)

为了理解import语句中花括号的使用,首先,您必须了解 ES6 破坏的概念>

  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'];
    
  3. 现在我们已经解决了这个问题,在 ES6 中,您可以导出多个模块。然后,您可以使用下面的对象解构

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

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

    您希望将导出的函数导入index.js;

        import {printFirstname, printLastname} from './module.js'
    
        printFirstname('Taylor');
        printLastname('Swift');
    

    您也可以使用不同的变量名称

        import {printFirstname as pFname, printLastname as pLname} from './module.js'
    
        pFname('Taylor');
        pLanme('Swift');
    

答案 6 :(得分:5)

通常在导出函数时需要使用{}

if you have export const x 
你正在使用  import {x} from ''

if you use export default const x 

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

答案 7 :(得分:2)

摘要ES6个模块:

出口:

您有2种出口类型:

  1. 命名出口
  2. 默认导出,每个模块最多1个

语法:

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

进口:

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

  1. 对于命名导出,我们必须使用花括号和确切名称作为导出的声明(即变量,函数或类)。
  2. 对于默认导出,我们可以选择名称。

语法:

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

有趣的事物:

  1. 在花括号中使用逗号分隔的列表,并与导出的匹配名称进行命名导出。
  2. 使用您选择的名称而不使用花括号进行默认导出。

别名:

只要您想重命名已命名的导入,都可以通过别名来实现。语法如下:

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

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

答案 8 :(得分:1)

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?

答案 9 :(得分:0)

花括号在命名导出时仅用于导入。如果默认为导出,则不使用花括号导入。

答案 10 :(得分:0)

对于默认导出,我们在导入时不使用{}。

例如

player.js

export default vx;

index.js

import vx from './player';

index.js enter image description here

player.js enter image description here

如果要导入导出的所有内容,则使用* enter image description here

答案 11 :(得分:0)

  • 文件中是否有任何默认导出。无需在import语句中使用花括号。

  • 如果文件中有多个导出,那么我们需要在导入文件中使用花括号,以便可以导入。

  • 您可以在下面的youtube视频中找到使用花括号和默认语句的完全不同之处。

https://www.youtube.com/watch?v=tN-SYsGoDYo&t=130s