module.exports
exports
require
module은 단지 파일 하나에 불과하고 스크립트 하나는 모듈 하나이다.
module.exports는 내보내는 방법으로 말 그대로 module을 내보내는 것이다. 이 객체에 module을 담고 다른 file에서 require를 실행하면 그 결과로 module.exports해서 내보낸 module 객체를 return한다. 즉 객체에 담긴 module을 다른 file에서 사용할 수 있는 것이다.
exports는 단지 module.exports를 참조할 뿐이다. 결국 두 개는 같은 객체를 바라보고 있다.
만약 exports에 객체를 직접 할당하면 exports는 module.exports를 참조하지 않게되고 어떠한 module로도 담기지 않게된다.
다른 모듈을 불러오는 키워드로 현재 파일의 위치에 따라 상대경로로 확장자를 가진 모듈들을 불러올 수 있습니다.
const calcNum = require('./add.js');
es6에서 정식으로 도입된 모듈 시스템이 도입되었다.
import
export
가 새롭게 추가된 키워드
export에는 named export와 default export가 있다.
export const add = (a,b) => a+b;
const add = (a,b) => a+b;
const mul = (a,b) => a*b;
export { add, mull }
export default function (a,b) { return a+b; }
const add = (a,b) => a+b;
const mul = (a,b) => a*b;
export default { add, mull }
다른 파일에서 내보낸 모듈을 불러올 때 사용한다.
MDN을 보면 아래와 같은 방법으로 사용이 가능하다.
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
var promise = import("module-name");