본문 바로가기

개발일지

Node.js export 사용패턴 및 require 사용

20171113

날짜 : 2017. 11. 13.(월)

Node.js export 사용패턴 및 require 사용

생각하게 된 동기

  1. Node.js 참고자료 별 export를 사용하는 방식이 다르다.
  2. 사용방식별 차이가 있는지 확인을 하고 싶다.
  3. require 경우 "require()()"사용하는 패턴이 있는데 어떠한 원리인지 알고 싶다.

조사한 내용 정리

exports

  1. 목적 : 객체를 모듈화하여 다른곳에서도 사용을 할 수 있다.
  2. 사용되는 명령어
    • module.exports
    • exports 2가지가 존재하며, 2가지에는 기능상 다른 점이 없다.
  3. 사용패턴(해당 내용은 공식문서에 나온것이 아니니 참고만 하시기 바랍니다.)
    1. 객체별 export명령어 입력
exports.plus = function(a, b) {
  return a + b;
};
   
exports.multiply = function(a, b) {
  return a * b;
};
  1. 마지막줄에 별도 객체를 만들어서 입력
var plus = function(a, b) {
  return a + b;
};
   
var multiply = function(a, b) {
  return a * b;
};
module.exports = {
    plus : plus, 
    multiply : multiply
};
  1. 처음부터 객체에 담아서 코딩을 한 뒤, 마지막에 객체 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;

주의사항

  1. 동일한 객체의 이름이 여러번 사용되면 최초의 객체만 exports 된다.
module.exports.hello = true; // Exported from require of module
exports = { hello: false };  // Not exported, only available in the module
  1. exports라는 객체를 만들어서 모듈화 시키면 기존의 exports모듈이 제할당되어 사용이 안된다.
module.exports = exports = function Constructor() {
  // ... etc.
};

require

  1. exports 된 모듈을 사용하기 위한 방법
    • require('모듈명')
  2. 모듈의 설정파일을 모듈에 적용하여 불러오고 싶을때
    • require('설정파일')('모듈명')
    • 해당 방법이 가능한 이유는 require모듈안에 require가 존재 하기 때문
~ $ node
> require('module').wrapper
[ '(function (exports, require, module, __filename, __dirname) { ',
  '\n});' ]
>

참고자료

  1. opentutorials 컨텐츠
  2. 공식문서 - global object
  3. 공식문서 - exports shortcut
  4. 공식문서 - modules
  5. zerocho - nodemodule 시스템
  6. Sammer Buna's post
  7. hochulshin's post