首页 文章

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

提问于
浏览
490

这似乎是显而易见的,但我发现自己对于何时使用花括号在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帖子没有回答我的问题,而是我在问我何时应该或不应该使用花括号来导入 single 模块,或者我不应该使用花括号来导入ES6中的单个模块(这显然不是例如,我已经看过需要大括号的单一导入)

9 回答

  • 0

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

    关于import语句如何与示例一起工作的简单演示可以在我自己对When do we use '{ }' in javascript imports?中类似问题的回答中找到

  • 1

    为了理解 import 语句中花括号的使用,首先,您必须了解 ES6 中引入的 destructing 的概念

    • 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
    
    • Array destructuring
    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'];
    

    现在我们已经完成了这项工作,在 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');
    
  • 32

    这是 default import

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

    仅当 A 具有 default export 时它才有效:

    // A.js
    export default 42
    

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

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

    因为它总是会解决 AA .


    这是 named import called A

    import { A } from './A'
    

    仅当 A 包含 named export called A 时才有效:

    export const A = 42
    

    在这种情况下,名称很重要,因为您要导入 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!
    

    要使这些工作,您将 corresponding named export 添加到 A

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

    模块只能有 one default export ,但 as many named exports as you'd like (零,一,二或多) . 您可以将它们全部导入:

    // 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.

  • 1485

    如果你认为 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';
    
  • 54

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

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

  • 1

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

    if you have export const x
    

    你用 import {x} from ''

    if you use export default const x
    

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

  • 88

    摘要ES6模块:

    exports:

    您有两种类型的出口:

    • 命名出口

    • 默认导出, Max 1 per module

    Syntax:

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

    Imports:

    type of export (即命名或默认导出)会影响如何导入内容:

    • 对于命名导出,我们必须使用花括号和 exact name 作为导出的声明(即变量,函数或类) .

    • 对于默认导出,我们可以选择名称 .

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

    感兴趣的东西:

    • 在大括号内使用逗号分隔列表,并使用导出的 matching name 进行命名导出 .

    • 使用您选择的名称而不使用花括号进行默认导出 .

    别名:

    每当您想要重命名命名导入时,都可以通过 aliases 进行重命名 . 其语法如下:

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

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

  • 0

    我想说 import ES6关键字也有一个星号表示值得一提 .

    enter image description here

    如果您尝试控制日志混合:

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

    你会得到:

    enter image description here

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

    当您只需要模块中的特定组件时,括号是金色的,这样可以为webpack等捆绑器创建更小的占用空间 .

  • 10

    Dan Abramov上面的回答解释了 default exportsnamed exports .

    Which to use?

    引用大卫赫尔曼:ECMAScript 6支持单/默认导出样式,并为导入默认值提供最甜蜜的语法 . 导入命名导出可以,甚至应该略微简洁 .

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

    总体使用你喜欢的任何 .

    Additional

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

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

相关问题