본문 바로가기
IT/자바스크립트

[javascript] es6 export, import 사용하기

by 모찌 2018. 8. 11.

javascript 의 export와 import는 es6(es2015) 에서 모듈 시스템을 이용하여 사용하기 위해 정의된 API이다.


하지만 몇몇 브라우저에서는 아직 지원하지 않기 때문에 webpack같은 도구를 통한 번들 작업이 필요하다.


이번 포스팅에서는 그 각각의 사용법을 알아보자.


1. export 


export 는 내부 스크립트 객체를 외부 스크립트로 모듈화하는 것이다.


물론, export를 선언하지 않았으면 외부 스크립트에서 import를 통해 사용할 수 없다.


export는 스크립트 내 모든 객체에 선언할 수 있다. 


export 방식에는 Named와 default 방식이 있다.


named export 방식


//각각 선언
export const exString = 'string';
export const exArray = [1,2,3];
export const exObject = {object: 'object'};
export function consoleFunction(target) {
console.log(target);
}

export {consoleFunction as conFunc, exString, exArray, exObject}; //한번에 선언


named export를 사용한다면 import하는 스크립트에서 위와 같이 정해진 이름으로 사용해야 한다.


하지만 위와 같이 import할 때, as를 통해 변경할 수 있다. 


default export 방식


export default consoleFunction; //단일 선언
export {consoleFunction as default, exString, exArray, exObject}; //다른 객체와 같이 선언


위와 같이 export뒤에 default를 선언하면 된다.


이 default는 한 객체에만 선언할 수 있기 때문에 해당 스크립트의 메인 객체에만 선언하는 것이 좋다.


default를 선언하면 이 스크립트를 사용하는 곳에서 해당 객체를 원하는 변수명으로 선언하여 사용할 수 있다.


주의해야 할 점은 default는 const, let, var와 함께 선언하지 못한다.



re-export


import로 가져온 객체들은 다시 export를 선언할 수 있다. 


default로 받아온 객체는 다음과 같이 as를 이용해서 변수명을 정해서 export를 선언할 수 있다.

export {default as log, exString} from './Export.js';

imprt해온 모든 객체를 내보내야한다면 다음과 같다.

export * from './Export.js';


2. import


import를 선언하여 외부 스크립트에서 export를 선언한 객체를 가져와서 사용하자.


named export를 선언한 객체 import


import {exString, exArray, exObject} from "./Export"; //각각 선언
import * as module from "./Export"; //한번에 선언
module.exString;
module.exArray;
module.exObject;


default export를 선언한 객체 import

import log from './Export.js'; //default만 선언

import log, {exString, exArray, exObject} from './Export.js'; //다른 것과 같이 가져오기

import {default as log, exString, exArray, exObject} from './Export.js'; //같은 객체에서 선언


예시

많은 방법을 통해 export와 import하도록 코드를 작성하였으니 일관성이 없다.


Export.js

export {consoleFunction as default, exString, exArray, exObject};

const exString = 'string';
const exArray = [1, 2, 3];
const exObject = {object: 'object'};
function consoleFunction(target) {
console.log(target);
}


Import.js


import log, {exString, exArray, exObject} from './Export.js';
export {default as reExportLog, exString} from './Export.js';

log(exString);
log(exArray);
log(exObject);


reExportImport.js


import * as importJs from './Import.js';

importJs.reExportLog(importJs.exString);


결과

'string'
[1, 2, 3]
{object: "object"}
'string'




댓글