10월 15일 (금) 모듈(module)

Southbig·2021년 10월 15일
0

모듈이란 ?

  • 모듈이란 관련된 코드들을 하나의 코드 단위로 캡슐화 하는 것
  • 모듈이란 관련된 객체들의 집합소
    어떠한 기능을 수행하기 위해 함수 또는 객체들을 만들어 놨으면.
    그걸 한 JS의 파일에 써놓기엔 가독성이나 유지보수가 좋지 않아서 관련 함수 또는 객체들을
    JS파일별로 따로 모아놓은것

Require()

Require()함수로 모듈을 가지고 온다
node.js에서는 모듈을 불러오기 위해 require()함수를 쓴다

require은 object를 반환한다

module.exports

one.js

// 표현 1
const template = { a: 'a', b: 'b' } 

module.exports = template; 

// 표현 2

module.exports = { a: 'a', b: 'b' }

two.js

const template = require('one.js'); 
console.log(template.a); // a

one.js 처럼 2가지 경우로 module.export 를 사용하여 모듈화를 시킬수 있다

그 모듈화 시킨걸 two.js 처럼 가져온다

exports

one.js

const module = { exports: {} };
const exports = module.exports;
...
return module.exports;

exports객체와 module.exports객체는 동일하다
exports와 module.exports가 같은 객체를 참조한다

exports 가 module.exports객체를 call by reference 방식으로 바라보고 있으며,
최종적으로 리턴값은 module.exports 다

일반코드

 one = function() {
  return 1;
 };
 two = function() {
  return 2;
 }

module.exports과 exports 코드 작성 방식

// number.js
// module.exports
module.export = {
 one: function() {
  return 1;
 },
 two: function() {
  return 2;
 }
};
//exports
exports.one = function() {
 return 1;
};
exports.tow = function() {
 return 2;
}

Require()를 사용하여 importing하기

require

// index.js
// const number = require("파일경로"); // require을 사용하여 importing
...
const number = require("./number.js");
...
number.one(); // 1
number.two(); // 2

exports 와 module.exports 의 차이점

exports는 property 방식을 쓰고 module.exports는 그냥 써도 무방하다

이유는 exports를 바로 써버리면 module.exports의 call by reference 관계를 끊어버려서
exports라는 변수가 되버리기 때문이다

  • exports 는 property 방식으로 사용
  • module.exports 는 바로 사용가능

exports 가 module.exports객체를 call by reference 방식으로 바라보고 있으며,
최종적으로 리턴값은 module.exports 다

모듈은 기본적으로 객체이고, 이 객체를 exports 와 module.exports가 모두 바라보고 있는데,
최종적으로 module.exports가 반환 된다

profile
즐겁게 살자

0개의 댓글