[node js] 모듈화 / require() / module.exports vs exports

HYEJIN·2022년 7월 25일
0

Node.js

목록 보기
1/4

module exports / require()

모듈로 다른 파일에서 위해서는 module의 exports속성을 활용하여 내보내고, exports 된 모듈을 이용하기 위해서는 require()로 모듈을 가져온다.

require('파일경로')

// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('node:crypto');

예시1)
https://velog.velcdn.com/images/hyejin_nk/post/72ddc74e-6df2-4390-83f8-00adf616eb36/image.png

예시2)
https://velog.velcdn.com/images/hyejin_nk/post/7fb90877-d985-430b-b58d-3e58897facf4/image.png

>> ES6에서 require대체할 import가 생겼는데, 이 부분은 후에 작성할 예정이다.


module.exports vs exports

var module = { exports: {} };
var exports = module.exports;
// your code 
return module.exports;
  • exports객체와 module.exports객체는 동일하다.
  • exports 가 module.exports객체를 call by reference 방식으로 바라보고 있으며, 최종적으로 리턴값은 module.exports
    >> exports에 값을 그냥 할당해버리면 새로운 변수가 됨으로 그렇게 지정하면 call by reference 관계가 끊어진다.

exports = {} //객체 할당 X
module.exports = {} //객체 할당 O

exports.kwak = 5; //속성 할당 O
module.exports.kwak = 5 //속성 할당 O
  • exports는 property 방식
  • module.exports는 객체를 할당하는 방식

module.exports는 빈 오브젝트로 초기화되어 있으므로 exports 변수를 통해 프로퍼티를 추가할 수 있지만, exports에 새로운 객체를 할당하면 module.exports와는 상관 없는 변수가 되어버리므로 모듈이 동작하지 않는다.

1) exports

  • exports는 module.exports를 참조
  • exports를 사용할 때는 exports 객체에 프로퍼티를 추가
// square.js
exports.area = (width) => width * width;
exports.perimeter = (width) => 4 * width;
// app.js
const square = require('./square'); 
console.log(square.area(3));
console.log(square.perimeter(3));

2) module.exports
module.exports 변수에 아예 새로운 객체를 할당 or 프로퍼티 할당도 가능

// square.js
module.exports = {
  area: (width) => width * width,
  perimeter: (width) => 4 * width
}

0개의 댓글