When should I use curly braces for ES6 import?

后端 未结 11 913
借酒劲吻你
借酒劲吻你 2020-11-21 09:46

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

11条回答
  •  清酒与你
    2020-11-21 10:32

    Summary ES6 modules:

    exports:

    You have 2 types of exports:

    1. Named exports
    2. Default exports, Max 1 per module

    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 name as the declaration (i.e. variable, function, or class) which was exported.
    2. For a default export we can choose the 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';   
    

    Things of interest:

    1. Use a comma separated list within curly braces with the matching name of the export for named export.
    2. Use a name of your choosing without curly braces for a default export.

    Aliases:

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

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

    Now we have imported importantData_1 but the identifier is myData instead of importantData_1.

提交回复
热议问题