JavaScript/JS 변수

module, exports, require

SMASMC 2024. 1. 30. 03:04

module

// math.js
module.exports = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  }
};
  • module은 현재 선언한 module에 대한 정보를 담고 있는 전역 객체이다. 다른 곳에서 module의 정보나 exports 객체를 직접 조작할 수 있다.

exports

// calculator.js
exports.add = function(a, b) {
    return a + b;
  };
  • exports 객체는 현재 모듈에서 다른 파일에 사용할 수 있도록 하는 객체이다. exports에 추가되는 모든 속성(함수, 변수 등)은 다른 파일에서 require을 통해 사용할 수 있다.

module 과 exports의 차이점

module은 객체 자체를 할당하기 때문에 참조가 끊기지 않는다. 반면에 exports는 module.exports를 기본적으로 참조하고 있는 관계이기 때문에 exports에 다른 객체를 할당하면 참조가 끊어질 수 있다.

Example )

// module.exports를 직접 할당
module.exports = {
  add: function(a, b) {
    return a + b;
  }
};

// exports에 추가
exports.subtract = function(a, b) {
  return a - b;
};

// exports에 다른 객체를 할당하면 참조가 끊길 수 있음
exports = {
  customMultiply: function(a, b) {
    return a * b;
  }
};

require

//require.js
const calculator = require('./calculator.js');

console.log(calculator.add(5, 3)); // 출력: 8

const math=require('./math.js');

console.log(math.add(1,2)); // 출력 : 3

console.log(math.subtract(3,6)); //출력 : -3
  • require은 module, exports에 선언된 인스턴스를 이용하여 함수를 사용할 수 있다.