1. export
1) commonJS
module.exports = hello;
exports.name = name;
2) ES6
- named exports 방식
export const name = 'Joe';
export function hello(name){
return 'hello' + name;
}
변수, 함수, 클래스 등의 선언문 앞에 export를 붙여 내보내는 방식으로, 여러 변수와 함수 등을 한꺼번에 내보내려면 아래와 같이 사용한다.
// export.js
export { name, hello };
// import.js
import {name, hello } from 'export';
- default export 방식
// export.js
export default hello;
// import.js
import hello from 'export';
하나의 모듈은 하나의 default export만 허용,
export default로 내보낸 모듈은 import 시 중괄호를 사용하지 않는다.
- as 키워드를 이용하여 다른 이름으로 내보낼 수 있다.
// export.js
export { hello as hi };
// import.js
import { hi } from 'export';
2. reqiure, export
1) commonJS
const hello = require('hello');
const hello = require('hello').hello;
2) ES6
- named exports 모듈 불러오기
import { hello } from 'hello';
- default export 모듈 불러오기
import hello from 'hello';
- as 키워드를 이용하여 다른 이름으로 불러올 수 있다.
import hello as hi from 'export';
- named exports 방식으로 내보낸 모듈을 아래와 같이 불러올 수 있다.
// export.js
export { name, helllo };
// import.js
import * as Module from 'export';
Module.name;
Module.hello();
*를 이용해서 export.js에서 내보낸 모듈을 Module 객체의 멤버로 만들어준다.
- named export와 default export를 함께 사용하는 모듈을 *로 불러온 경우
// export.js
export { name };
export default hello;
// import.js
import * as Module from 'export';
Module.name;
Module.default();
export.js에서 default export 방식으로 내보내진 모듈이 import.js 에서 Module 객체의 default 멤버로 추가된다.