[Node.js] CommonJS VS ES module

EUNCHAE KIM·2022년 10월 17일
0

1. CommonJS

The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java. The intention is that an application developer will be able to write an application using the CommonJS APIs and then run that application across different JavaScript interpreters and host environments

참고 : https://www.commonjs.org

  • Common : Javascript를 브라우저에서만 사용하는 언어가 아닌 일반적인 범용 언어로 사용할 수 있도록 하기 위해서 만든 모듈
  • 보내는 곳 : module.exports 객체에 사용하고 싶은 변수들을 넣어주기
  • 받는 곳 : 모듈 변수 이름 = require("./모듈 파일이름");
  • 동기적,블로킹, 파일 가져오는 방식
  • json 파일 쉽게 읽어 올 수 있다

For example, this is a CommonJS module that exports two functions:

module.exports.add = function(a, b) {
        return a + b;
} 

module.exports.subtract = function(a, b) {
        return a - b;
} 

We can also import the public functions into another Node.js script using require(), just as we do here:

const {add, subtract} = require('./util')

console.log(add(5, 5)) // 10
console.log(subtract(10, 5)) // 5

참고 : https://blog.logrocket.com/commonjs-vs-es-modules-node-js

2. ES modules

The ES module format is the official standard format to package JavaScript code for reuse and most modern web browsers natively support the modules.The ES module format was introduced in Node.js v8.5.0 as the JavaScript module system was standardized.

  • v15부터 ES module지원(v13,v14에도 사용가능하도록 다운포팅)
  • 보내는 곳 : 선언 앞에 export 키워드 붙여주기 or 마지막에 export{변수이름}
  • 받는 곳 : 파일 맨 앞에 import 키워드 from '파일 이름'
    코어자바스크립트 - 모듈
  • 애초에 Node.js는 모듈을 Asynchronous하게 읽어온다는 가정을 하지 않고 설계된 런타임이다. 그래서 기반부터 Synchronous하게 모듈을 읽어오게 되어있다. 기반 시스템에 변경을 해야하다보니 Node.js 위원회는 큰 고민에 빠지게 된다
    - 비동기로 모듈 가져오는 게 핵심
  • 많은 개발자들이 Node.js도 결국 ES module로 완전히 넘어가지 않을까라는 얘기가
    나오고 있다
  • 그러나 , Node.js 생태계의 많은 모듈들이 CommonJS로 개발되어있다는 점을 잊으면 안된다

For example, here’s a simple ES module (with an .mjs extension) exporting two functions for public use:

// util.mjs

export function add(a, b) {
        return a + b;
}

export function subtract(a, b) {
        return a - b;
}

We can then import both functions using the import statement:

// app.mjs

import {add, subtract} from './util.mjs'

console.log(add(5, 5)) // 10
console.log(subtract(10, 5)) // 5

Another way to enable ES modules in your project can be done by adding a "type: module" field inside the nearest package.json file (the same folder as the package you’re making):

{
  "name": "my-library",
  "version": "1.0.0",
  "type": "module",
  // ...
}
profile
Try Everything

0개의 댓글