외부 다른 파일에서도 쓸 수 있게 하는 것. (재사용성)
자바스크립트가 구동되는 호스트 환경에 따라 모듈화 방법이 다르게 제공된다.
웹 브라우저에서 로직을 모듈화 하는 방법은 html 내용을 다음과 같이 변경해서 해당 hello.js
파일에 모듈을 정의해서 사용한다.
<head><script src="hello.js"></script></head>
그리고 이 글은 Node.js에서 모듈을 로드하는 방법,
CommonJS(require
, module.exports
)에 대한 글이다.
모든 모듈은 자신만의 독립적인 실행 영역이 있어야 한다.
모듈 정의는 전역 객체인 exports 객체를 이용한다.
exports로 내보내진 모듈을 불러와서 사용하려면 require를 사용한다.
// hello.js
module.exports.anything = function(){
console.log("I am anything.");
}
아래의 runner.js파일에서 hello.js파일에 정의된 모듈을 쓰고싶다면?
// runner.js
const hello = require ('./hello');
// hello 변수에 가져온 모듈을 담아주면 runner.js파일에서 hello 변수로 모듈에 접근가능
console.log(hello); // {anything: Function}
hello.anything(); // "I am anything."
// hello.js
exports.anything = function() {
console.log('I am anything');
}
// runner-2.js
const hello = require ('./hello');
console.log(hello); // {anything: Function}
hello.anything(); // I am anything.
원래는 module.exports
를 써오다가 shortcut을 만든 것이 exports
라서 둘의 결과는 같다.
그런데 주의할 점이 있다.
둘의 기능은 같지만 섞어쓰지 말고 통일한다.
exports
를 쓸 거면 exports만
쓰고 module.exports
를 쓸 거면 module.exports만
쓴다.
이유?
module.exports
가 있다면, exports
가 무시된다.
exports
는 module.exports
사용을 도와주는 helper함수이다. exports
는 module.exports
를 참조하고 있는 (short-cut) 변수이다.
// hello.js
module.exports = {a : 1}
// runner.js
const hello = require('./hello');
console.log(hello); // {a : 1}
정상적으로 잘 exports된다.
문제는 exports
는 변수인데 변수에 직접 값을 할당해서 내보내면 exports
가 참조하고 있는 실제 module.exports
에는 아무런 영향이 없다.
따라서 runner.js에서 해당 모듈을 사용하는 코드를 적으면 원하는 응답을 받지못한다.
// hello.js
exports = {a : 1}
// runner.js
const hello = require('./hello');
console.log(hello); // { }
그냥 module.exports
만 쓰는 게 제일 안전할 것 같다😃
그리고 JavaScript ES6 부터 자바스크립트 자체에 모듈을 지원하는 import export가 생겼다.
@babel/node을 설치하고 import export를 사용하거나,
(모듈화 뿐 아니라 다른 ES6문법에서도 자유로워지기 때문에 이 방법이 나을 것 같다)
CommonJS 방식을 사용하면 된다.