모듈시스템(Module System, import/export)

2022. 1. 14. 09:00Programming Language/JavaScript(Node.js)

 

Node.js의 모듈시스템은 CommonJS와 ES 모듈이 있습니다.

 

  • CommonJS 모듈
    • require 함수를 사용하는 방법
    • module.exports와 exports의 차이
      module.exports: 실제로 export되는 객체
      exports: module.exports를 참조하는 변수
    • 먼저 기존의 CommonJS 방식을 이용해서 간단한 예제 모듈을 작성해보겠습니다.
      아래 time 모듈은 moment 패키지를 불러와서
      현재 시간을 문자열로 리턴하는 now() 함수를 내보내고 있습니다.
      // time.js
      
      const moment = require("moment");
      
      module.exports.now = function () {
          return moment().format();
      };​
       같은 방식으로 테스트 모듈도 작성해보겠습니다.
      아래 time.test 모듈은 time 모듈을 불러와서 now 함수의 호출 결과를 출력하고 있습니다.
      test.test.js 파일을 실행해보면 다음과 같이 예상대로 작동을 합니다.
      // time.test.js
      
      const { now } = require("./time");
      
      console.log("Now:", now());​
      $ node src/time.test.js
      Now: 2020-05-23T17:43:28-04:00​
       
  • ES 모듈
    • ES6에서 도입된 import 키워드를 사용하는 방법
    • 사용하려면 모든 파일을 .mjs 파일로 만들거나(ES 모듈에서는 .mjs로 확장자까지 명시해야됨)
      package.json에 "type": "module"을 추가해야된다.
      // time.mjs
      
      import moment from "moment";
      
      export function now() {
          return moment().format();
      }​
      // time.test.mjs
      
      import { now } from "./time.mjs";
      
      console.log("Now:", now());​
      {
          // ...
          "type": "module"
          // ...
      }​
       

 

 

 

 

 

 

Reference

https://www.daleseo.com/js-node-es-modules/

https://dydals5678.tistory.com/97

https://ko.javascript.info/modules