본문 바로가기

카테고리 없음

[Node] 노드 모듈 (Node Module) 이란? exports 와 module.exports 의 차이점

728x90

1. 모듈 (Module)

모듈은 여러 함수들의 집합을 의미한다.

애플리케이션을 구성하는 개별적인 요소이며, 보통 필요한 기능이 있을 때 가져와서 사용한다.

기능별로, 파일 단위로 분리되어 있기 때문에 유지보수성과 효율성이 높다.

 

1) 내장모듈과 외장모듈

노드 모듈은 내장모듈과 외장모듈로 나눠진다.

내장모듈은 node.js에서 제공되는 모듈로, 노드를 설치하기만하면 사용할 수 있다.

 

반면, 외장모듈은 일반 개발자들이 만든 모듈로 npm을 통해 설치해야 사용이 가능하다.

 

 

2) CommonJS

자바스크립트의 모듈화 명세를 만든 대표적인 그룹으로,

현재 node의 표준이 되는 명세이다.

간단하게 말하면 자바스크립트 파일 간의 의존성을 어떻게 가지게 할지 정해준다.

 

//counter.js
let count = 0;

function increase(){
    count++;
}

function getCount(){
    return count;
}

module.exports.getCount = getCount;
module.exports.increase = increase;


//app.js
const counter = require('./counter.js');

counter.increase();
console.log(counter.getCount());

commonJS임을 알 수 있는 가장 큰 특징인 require와 module.exports라고 볼 수 있다.

node.js에서 모듈을 가져오거나 내보낼땐, require와 module.exports를 사용한다.

 

노드도 commonJS를 기본으로 하고 있기 때문에 

모듈을 사용하기 위해선 require과 module.exports를 사용해야 한다.

 

 

* module.exports 와 exports 의 차이점

 

다른사람들이 작성한 노드 코드들을 봅면 exports를 쓸 때도 있고, module.exports를 사용할때도 있다.

그렇다면 둘의 차이점은 무엇일까?

 

module.exports와 exports는 같은 객체를 바라보고 있지만,

엄연히 다른 식별자이며 exports는 단순히 module.exports를 참조한다.

 

module.exports는 반환되지만 exports는 반환되지 않는다. 

간단히 말하면, exports는 모듈 작성자가 코드를 덜 작성하도록 돕는다고 생각하면 된다. 

 

exports = obj;


{}  < module.exports & exports 가 참조

exports = obj 

{} < module.exports 
obj < exports  //exports의 참조값이 바뀜

따라서 만일 exports에 obj를 따로 할당한다면, require() 함수에 의해 값을 가져올 수 없게 된다.

exports의 참조값이 바뀌기 때문이다.

 

exports는 반환되지 않기 때문에 module.exports가 아닌 다른 객체를 바라보게되면,

require() 에 의해 모듈을 가져올 수 없게 된다.

 

exports.add = fun...

만일 exports로 모듈을 내보내고 싶다면, 위와 같이 exports property(프로퍼티)에 값을 지정해줘야한다.

그래야 exports의 참조값이 변하지 않고, module.exports 안에 있는 프로퍼티가 변경되기 때문이다.

 

 

 

3) ES6

//counter.js
let count = 0;

export function increase(){
    count++;
}

export function getCount(){
    return count;
}

//app.js
import { increase, getCount } from './counter.js'

increase();
console.log(getCount());

ES6에서 import, export 기능이 추가되며,

자바스크립트만으로도 모듈을 가져오고, 내보내는것이 가능해졌다.

 

//package.json
{
  "name": "4-module",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",  //타입 설정으로 자바스크립트 자체 모듈을 사용한다고 입력해줌
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

단, node는 commonJS가 기본이기 때문에 package.json type을 module로 설정해

자바스크립트 자체 모듈을 사용한다고 입력해줘야 한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90