[javascript] module.exports, exports, require

Chanho Yoon·2021년 7월 9일
0

javascript

목록 보기
3/3

CommonJS

module.exports exports require

module ?

module은 단지 파일 하나에 불과하고 스크립트 하나는 모듈 하나이다.

module.exports

module.exports는 내보내는 방법으로 말 그대로 module을 내보내는 것이다. 이 객체에 module을 담고 다른 file에서 require를 실행하면 그 결과로 module.exports해서 내보낸 module 객체를 return한다. 즉 객체에 담긴 module을 다른 file에서 사용할 수 있는 것이다.

exports??

exports는 단지 module.exports를 참조할 뿐이다. 결국 두 개는 같은 객체를 바라보고 있다.

만약 exports에 객체를 직접 할당하면 exportsmodule.exports를 참조하지 않게되고 어떠한 module로도 담기지 않게된다.

require

다른 모듈을 불러오는 키워드로 현재 파일의 위치에 따라 상대경로로 확장자를 가진 모듈들을 불러올 수 있습니다.

const calcNum = require('./add.js');

ES6

es6에서 정식으로 도입된 모듈 시스템이 도입되었다.
import export가 새롭게 추가된 키워드

export

export에는 named exportdefault export가 있다.

  • named export는 선언된 변수명 그대로 export 한다.
export const add = (a,b) => a+b;

const add = (a,b) => a+b;
const mul = (a,b) => a*b;
export { add, mull }
  • default export 모듈내에서 오직 하나만 존재할 수 있다.
export default function (a,b) { return a+b; }

const add = (a,b) => a+b;
const mul = (a,b) => a*b; 
export default { add, mull }

import

다른 파일에서 내보낸 모듈을 불러올 때 사용한다.
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");

0개의 댓글