날짜 : 2017. 11. 13.(월)
Node.js export 사용패턴 및 require 사용
생각하게 된 동기
- Node.js 참고자료 별 export를 사용하는 방식이 다르다.
- 사용방식별 차이가 있는지 확인을 하고 싶다.
- require 경우 "require()()"사용하는 패턴이 있는데 어떠한 원리인지 알고 싶다.
조사한 내용 정리
exports
- 목적 : 객체를 모듈화하여 다른곳에서도 사용을 할 수 있다.
- 사용되는 명령어
- module.exports
- exports 2가지가 존재하며, 2가지에는 기능상 다른 점이 없다.
- 사용패턴(해당 내용은 공식문서에 나온것이 아니니 참고만 하시기 바랍니다.)
- 객체별 export명령어 입력
exports.plus = function(a, b) {
return a + b;
};
exports.multiply = function(a, b) {
return a * b;
};
- 마지막줄에 별도 객체를 만들어서 입력
var plus = function(a, b) {
return a + b;
};
var multiply = function(a, b) {
return a * b;
};
module.exports = {
plus : plus,
multiply : multiply
};
- 처음부터 객체에 담아서 코딩을 한 뒤, 마지막에 객체 1가지만 exports
function Math(val) {
this.init_val = val;
}
Math.prototype.plus = function plus(a, b){
return this.init_val + a + b;
}
Math.prototype.multiply = function multiply(a, b){
return this.init_val * a * b;
}
module.exports = Math;
주의사항
- 동일한 객체의 이름이 여러번 사용되면 최초의 객체만 exports 된다.
module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module
- exports라는 객체를 만들어서 모듈화 시키면 기존의 exports모듈이 제할당되어 사용이 안된다.
module.exports = exports = function Constructor() {
// ... etc.
};
require
- exports 된 모듈을 사용하기 위한 방법
- require('모듈명')
- 모듈의 설정파일을 모듈에 적용하여 불러오고 싶을때
- require('설정파일')('모듈명')
- 해당 방법이 가능한 이유는 require모듈안에 require가 존재 하기 때문
~ $ node
> require('module').wrapper
[ '(function (exports, require, module, __filename, __dirname) { ',
'\n});' ]
>
참고자료
'개발일지' 카테고리의 다른 글
react와 boostrap과 reactbootstrap. (0) | 2017.11.20 |
---|---|
jugglingdb, 도전, 피드백, 성공적, 실패 (0) | 2017.11.14 |
Nodejs Stream 잘못 이해했던 부분과 DB사용이유 (0) | 2017.11.08 |
Nodejs Stream 그뤠잇 (0) | 2017.11.07 |
책이 항상 옳은 것이 아니구나 ... (0) | 2017.11.06 |