[Node.js] Module.exports

Zero·2023년 3월 12일

Node

목록 보기
2/11

모듈 (Module) 이란 ?

모듈이란 관련된 코드들을 하나의 코드 단위로 캡슐화 하는 것을 말한다. Node.js 에서 예시를 살펴보자 다음과 같은 greeting.js 라는 파일이 있을 때, 이 파일은 두개의 함수를 포함하고 있다.

// greeting.js
sayHelloInKorea = () => {
 	return "안녕하세요" 
};
sayHelloInEnglish = () => {
 	return "Hello" 
};


모듈 추출하기 (exporting)

greeting.js 의 코드가 다른 파일에서 사용될 때 그 효용성이 증가하는데, 이러한 일을 하기 위해서는 다음과 같이 작성하면 된다

sayHelloInKorea = () => {
 	return "안녕하세요" 
};
sayHelloInEnglish = () => {
 	return "Hello" 
};

module.exports.sayHelloInKorea = sayHelloInKorea;
module.exports.sayHelloInEnglish = sayHelloInEnglish;

// 또는 
exports.sayHelloInKorea = () => {
 	return "안녕하세요"
};
exports.sayHelloInEnglish = () => {
	return "Hello"
};

--> eportsmodule.exports.~로 대체할 수 있으며 조금 더 간략한 구문이라고 생각하면 된다.



모듈 사용하기 (importing)

app.js라는 새로운 파일에서 greeting.js의 메소드를 사용할 수 있도록 import 하는 과정은 다음과 같다.

require

var say = require('./greeting');

say.sayHelloInKorea() // 안녕하세요
say.sayHelloInEnglish() // "Hello"


정리

require 키워드는 object를 반환한다. 그리고 module.exports와 exports는 call by reference로 동일한 객체를 바라보고 있으며, 리턴되는 값은 항상 module.exports이다.

모듈은 기본적으로 객체이며, 이 객체를 module.exports, exports 모두 바라보고 있는데 최종적으로 return 되는 것은 무조건 module.exports라는 것이다.



예시

//math.js

const add = (x,y) => x+ y;

const PI = 3.14159;

const square = x => x * x;


module.exports.add = add;
module.exports.PI = PI;
module.exports.square = square;
--------------------------------------------------------

// app.js
const math = require('./math');
console.log(math);

--> 결과

0개의 댓글