export 문은 지정된 파일(또는 모듈)에서 함수 또는 오브젝트, 원시 타입들을 export 하는데 사용됩니다.
Note: 이 기능은 현재 기본적으로 어떤 브라우저에서도 구현되어있지 않습니다. Traceur Compiler, Babel, Rollup 과 같은 많은 트랜스파일러에서 구현이 되어있습니다.
문법
export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // 또는 var
export let name1 = …, name2 = …, …, nameN; // 또는 var, const
export default expression;
export default function (…) { … } // 또는 class, function*
export default function name1(…) { … } // 또는 class, function*
export { name1 as default, … };
export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
nameN- 내보낼 식별자 이름 (
import를 통해 다른 스크립트에서 가져올 수 있습니다).
설명
export는 두 가지의 다른 타입이 있는데, 각각의 타입은 위의 문법 중 하나에 대응됩니다:
- Named exports:
export { myFunction }; // exports a function declared earlier export const foo = Math.sqrt(2); // 상수 exports - Default exports (스크립트 당 딱 하나):
export default myFunctionOrClass // 여기에는 세미콜론이 없습니다.
Named exports는 여러 값을 export 하는데 유용합니다. import하는 동안, 해당 값을 참조하기 위해 같은 이름을 사용할 수 있습니다.
default export의 경우, 모듈 당 딱 하나의 default export가 있습니다. default export는 함수 또는 클래스, 오브젝트, 혹은 다른 것들이 될 수 있습니다. 이값은 가장 간단하게 import 할 수 있도록 하기 때문에 내보낼 값 중 "메인"에 해당하는 값으로 고려해야합니다.
예제
named exports 사용하기
모듈에서 우리는 다음과 같은 코드를 사용할 수 있습니다:
// module "my-module.js"
export function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { foo };
이 방법으로 우리는 다른 스크립트에서 사용할 수 있습니다(cf. import):
import { cube, foo } from 'my-module.js';
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
default export 사용하기
우리가 단일 값을 내보내거나 모듈에 대한 대체 값을 원한다면 우리는 default export를 사용할 수 있습니다:
// module "my-module.js"
let cube = function cube(x) {
return x * x * x;
}
export default cube;
그런 다음, 다른 스크립트에서 default export를 가져오는 것은 간단합니다:
import cube from 'my-module'; console.log(cube(3)); // 27
export default를 사용할 때, var, let 혹은 const는 사용하지 못합니다.
명세
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Exports' in that specification. |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Exports' in that specification. |
Draft |
브라우저 호환
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | No support | No support | No support | No support | No support |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | No support | No support | No support | No support | No support | No support |
참고
import- ES6 in Depth: Modules, Hacks blog post by Jason Orendorff
- Axel Rauschmayer's book: "Exploring JS: Modules"