program tip

ES6 가져 오기에 언제 중괄호를 사용해야합니까?

radiobox 2020. 10. 2. 21:58
반응형

ES6 가져 오기에 언제 중괄호를 사용해야합니까?


분명해 보이지만 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) {
// ...
}

중괄호가있는 내 구성 요소에서도 비슷한 오류가 발생합니다. 단일 가져 오기에 언제 중괄호를 사용해야하는지 궁금했습니다. 왜냐하면 여러 구성 요소 / 모듈을 가져올 때 중괄호로 묶어야하기 때문입니다.

편집하다:

에서의 SO 포스트 여기가 대신 내가 질문하고, 내 질문에 대답하지 않는 경우에 내가 나 가져 오기위한 중괄호를 사용하지 말아야 하나 이 명백하게하지 (모듈, 또는 나는 ES6에 하나의 모듈을 가져 오기위한 중괄호를 사용해서는 안 경우, 중괄호가 필요한 단일 가져 오기를 보았으므로)


이것은 기본 가져 오기입니다 .

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

모듈은 하나의 기본 내보내기 만 가질 수 있지만 원하는 만큼 이름이 지정된 내보내기를 가질 수 있습니다 (0, 1, 2 또는 여러 개). 모두 함께 가져올 수 있습니다.

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

여기, 우리는 기본으로 수출 수입 A및라는 이름의 수출을 myA하고 Something각각.

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

기본 내보내기는 일반적으로 모듈에서 가져올 것으로 예상되는 모든 항목에 사용되는 경향이 있습니다. 명명 된 내보내기는 편리한 유틸리티에 사용되는 경향이 있지만 항상 필요한 것은 아닙니다. 그러나 항목을 내보내는 방법을 선택하는 것은 사용자에게 달려 있습니다. 예를 들어 모듈에 기본 내보내기가 전혀 없을 수 있습니다.

이것은 기본 내보내기와 명명 된 내보내기의 차이점을 설명하는 ES 모듈에 대한 훌륭한 가이드입니다.


TL; DR : 기본이 아닌 내보내기를 가져 오려는 경우 중괄호가 사용됩니다.

자세한 내용은 위의 Dan Abramovs 답변을 참조하십시오.


import언급 할 가치가 있는 ES6 키워드에 대한 별표 표기법도 있습니다 .

enter image description here

콘솔 로그 Mix를 시도하는 경우 :

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

다음을 얻을 수 있습니다.

enter image description here

ES6 가져 오기에 언제 중괄호를 사용해야합니까?

The brackets are golden when you need only specific components from the module, which makes smaller footprints for bundlers like webpack.


Dan Abramov answer above explains about the default exports and named exports.

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.

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.

Overall use whatever you prefer.

Additional

Default export is actually a named export with name default, so default export can be imported as:

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

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

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

usually when you export a function you need to use the {}

if you have export const x 

you use 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


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_1 = 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.


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?

참고URL : https://stackoverflow.com/questions/36795819/when-should-i-use-curly-braces-for-es6-import

반응형