본문 바로가기

[자바스크립트] module.export, exports

 

 

 

들어가며

모듈을 만들고 활용하면서 module.export, exports에 대한 명확한 이해 없이 개념을 활용하고 있다는 것을 알았습니다. 이번 기회에 이 개념들을 명확하게 이해해야겠다고 생각했습니다. 

 

 

 

 


 

 

 

 

module.exports, exports 는 무엇일까?

개발을 하다보면, 특정 코드를 모듈화 할 때 module.exports, exports, export, export default를 사용하곤 합니다. 뭐가 이렇게 많아? 생각하실 수 있습니다. 먼저 module.exports와 exports에 대해 차근차근 알아보겠습니다.

 

 예를 들어 아래와 같은 코드가 있다고 보겠습니다.

 

 

 // app.js
 
 var Person = function(name) {
    this.name = name;
  }
  
  Person.prototype.getName = function() {
    return this.name;
  }
  
  var test = new Person('test');
  
  module.exports = test
  
  
// person.js
var person = require('./app.js');
console.log(person);

 

 

위와 같은 코드가 있을 때, person의 console.log를 실행해보면 아래와 같은 결과를 만날 수 있습니다.

 

 

Person { name: 'test' }

 

그럼 module.exports가 아닌 exports만 사용했을 땐 어떤 결과를 얻을 수 있을까요?

 

 

 // app.js
 
 var Person = function(name) {
    this.name = name;
  }
  
  Person.prototype.getName = function() {
    return this.name;
  }
  
  var test = new Person('test');
  
  exports = test
  
  
// person.js
var person = require('./app.js');
console.log(person);
{}

 

 

위와 같이 exports를 사용했을 때 다시 우리가 원하는 {} 빈 객체만 출력이 된 것을 볼 수 있습니다. 그럼 exports에 접근자를 사용해서 값을 할당하는 경우는 어떻게 설정이 될까요? 아래를 살펴보겠습니다.

 

 

 // app.js
 
 var Person = function(name) {
    this.name = name;
  }
  
  Person.prototype.getName = function() {
    return this.name;
  }
  
  var test = new Person('test');
  
  exports.test = test
  
  
// person.js
var person = require('./app.js');
console.log(person);

 

{ test: Person { name: 'test' } }

 

 

위와 같이 exports에 test라는 객체를 추가하고, 그 객체의 값에 모듈을 할당했습니다. 즉 접근자를 사용했을 때 위와 같은 값이 출력되는 것을 볼 수 있었습니다. 그럼 왜 module.exports를 사용하면 원하는 값을 불러올 수 있는데, 왜 exports만 사용하면 빈 객체만 출력이 되는 것일까요? 그리고 왜 exports에 접근자를 사용했을 땐 값이 출력되는 것일까요? 알아보겠습니다. 

 

 

 

Module {
  id: '.',
  path: '/',
  exports: Person { name: 'test' },
  filename: '/app.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/node_modules',
    '/node_modules'
  ]
}

 

 

모듈을 콘솔에 출력해봤습니다. module.exports로 모듈을 만든다면, module이라는 객체의 exports키에 값이 할당되는 것을 알 수 있습니다. 하지만 module.exports가 아닌 exports만 활용한다면 아래와 같은 결과를 얻을 수 있습니다. 

 

 

Module {
  id: '.',
  path: '/',
  exports: {},
  filename: '/app.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/node_modules',
    '/node_modules'
  ]
}

 

 

즉 exports만 활용하면, module객체에 키 값으로 추가해주는 것이 아니라는 것을 알 수 있습니다. 그럼 exports에 접근자를 활용해서 키 값을 추가하면 어떻게 되는지 알아보겠습니다.

 

 

Module {
  id: '.',
  path: '/',
  exports: { test: Person { name: 'test' } },
  filename: '/app.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/node_modules',
    '/node_modules'
  ]
}

 

 

위와 같이 exports 객체에 키와 값이 포함된 객체가 값으로 할당된 것을 볼 수 있습니다. 그렇다면, module.exports와 exports는 서로 어떤 관계일까요? 사실 exports는 call by reference로 module.exports를 바라보고 있고, 리턴되는 값은 항상 module.exports입니다. 이 관계를 코드로 표현해보면 아래와 같습니다.

 

 

var module = {
	exports: {}
};
var exports = module.exports;

return module.exports;

 

 

 

기본적으로 module.exports, exports 모두 하나의 객체를 바라보고 있는데, 최종적으로 return 되는 것은 무조건 module.exports라는 것입니다. exports에 멤버를 추가하면, 결국 module.exports에도 같은 멤버가 추가되는 것입니다.

 

 

 

 

하지만 결국 최종적으로 리턴되는 것은 module.exports 입니다. 만약 exports에 다른 객체를 할당하게 되면, module.exports의 객체와 달라지게 되고, exports에 어떤 변경을 해도 모듈에는 영향을 주지 못합니다. 

 

 

 

그럼 export는 무엇일까요? 예를 들어 살펴보겠습니다.

 

export const a = 1;
export default b = 2;

 

위의 예시에서 default가 붙으면 import할 때 괄호를 붙이지 않아도 됩니다. 또한 default가 아닌 일반 export의 경우는 as c처럼 해당 파일에서 변수 이름을 변경할 수 있습니다.

 

import b, {a as c} from './somewhere';

 

 

만약 import * from './somewhere' 라고 하면 export 한 모든 값을 import 하게 됩니다.

 

 

 

 

 


 

 

 

 

마치며

헷갈리던 부분을 정리하면서 아직도 기본기가 부족하다는 점을 많이 깨닫습니다. 앞으로 기본기 있는 개발자가 되기 위해 더욱 정진하겠습니다. 

 

 

 

 

 

 


 

 

 

 

 

 

 

출처

 

[NodeJS] module.exports 와 exports 의 차이점

Express 에 대해서 분석하다보니, Router 부분에서 다소 익숙치 않은 부분을 발견했다. 아래와 같이 module.exports 에 객체를 직접 대입하는 부분이었는데, 항상 exports 아래에 프로퍼티로 값을 추가해주

programmingsummaries.tistory.com

 

[javascript] ES6 export vs NodeJS module.exports와 exports의 차이

모듈 NodeJS에서의 모듈 모듈이란 관련된 코드를 하나의 코드 단위로 캡슐화 하는 것을 말한다. 여러개의 코드로 분할하여 관리하고 index.js 파일 하나에 전부 import 시켜 효율적으로 코드를 관리할

mber.tistory.com

 

NODE JS - 모듈이란? , module.export 와 exports의 차이

◎ 모듈이란? ​ ▼ 내용 모듈이란 관련된 객체들의 집합소. 어떠한 기능을 수행하기 위해 함수 또는 객체들을 만들어 놨으면. 그걸 한 .js의 파일에 써놓기엔 가독성이나 유지보수가 좋지 않아

dydals5678.tistory.com

 

 

모듈 내보내고 가져오기

 

ko.javascript.info