When should I use curly braces for ES6 import?

后端 未结 11 942
借酒劲吻你
借酒劲吻你 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:36

    In order to understand the use of curly braces in import statements, first, you have to understand the concept of destructing introduced in 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

    Let's assume you have a module called 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;

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

提交回复
热议问题