Javascript
파일 단위로 분리된 코드
1. 하나의 모듈에서 다른 모듈을 호출하여 사용
2. 모듈은 그 자체로도 하나의 프로그램이면서 다른 프로그램의 부품으로 사용 가능
3. 보통 1개의 파일에 1개의 모듈
- 모듈이 필요한 이유
- 모듈 사용 방법
export 명령어를 변수나 함수 앞에 붙이면 외부 모듈에서 해당 변수나 함수에 접근 가능
import, require 명령어를 사용하면 외부 모듈의 기능을 가져올 수 있음
=> require -> commonJS / import -> ES6
module.exports = router;
- 모듈 사용해보기
modules/math.js
// modules/math.js
function add(a, b) {
return a + b;
}
module.exports = add;
modules/run.js
// modules/run.js
const add = require("./math");
console.log(add(3, 4));
// Print: 7
함수 하나하나를 밖으로 내보내 주는 방법
const {add} = require("./math.js"); // 객체구조분해할당
exports
/** 화살표 함수 exports **/
// 모듈을 호출했을 때, add 키 값에는 add 변수 함수가 가지고 있는 값이 할당된다.
const add = (a, b) => {
return a + b;
}
exports.add = add;
exports
/** 익명 함수 exports **/
// 모듈을 호출했을 때, add 키 값에는 (a,b){return a + b;} 익명 함수가 할당되는 방법
exports.add = function (a, b) {
return a + b;
}
const {add} = require("./math.js");
Module.exports = Object
/** Module.exports = Object **/
// 모듈을 호출했을 때, add 키 값에는 add 함수가 들어가는 방법이다.
function add(a, b) {
return a + b;
}
module.exports = { add: add };
module.exportts = Function
/** module.exports = Function **/
// 모듈 그 자체를 add 함수로 할당
function add(a, b) {
return a + b;
}
module.exports = add;