node.js 모듈 시스템 esm과 commonjs
수정일: 2025. 9. 14.
module system: commonJS VS ECMAScript Modules (ESM)
모듈 시스템은 node.js 환경에서 파일과 파일의 연결을 어떻게 처리할 것인지를 가리킵니다.
크게 commonJS와 ECMAScript Modules로 나뉜다.
module system을 선택하자
node.js 환경에서 아무런 설정을 하지 않을 경우 사용되는 모듈 시스템은 commonJS 이다. 이를 ESM으로 변경하려면
package.json > type: "module"로 변경해주면 됩니다.
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type":"module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.13.1"
}
commonJS
commonJS를 사용하는 경우 아래와 같은 형식을 가집니다.
// add.js (CommonJS)
function add(a, b) {
return a + b;
}
module.exports = { add };
// main.js
const { add } = require('./add.js');
console.log(add(1, 2)); // 3
module
module은 아래와 같은 형식을 가집니다.
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './add.js';
console.log(add(1, 2)); // 3