mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

tooling

ESM과 CommonJS.

import/export vs require/module.exports, bundler, Node, tree shaking 관계.

  • ESM (ES Modules): import / export정적 분석, tree shaking 가능
  • CJS (CommonJS): require / module.exports — Node 전통, 동적 로드

📦 ESM

import { useState } from 'react';
export default function App() {}
export { helper };
  • import()dynamic import, code splitting
  • package.json: "type": "module".js 파일 ESM
  • browser native ESM — <script type="module">

📦 CommonJS

const fs = require('fs');
module.exports = { read };
  • require() — runtime, 조건문 안 가능 (static import와 대비)
  • Node legacy, npm 패키지 다수 CJS

🧰 Bundler 관점

ESM 정적 그래프와 CommonJS 런타임 로딩

  • Webpack/Vite — ESM/CJS 둘 다 그래프에 넣어 하나의 bundle/chunk로

  • ESM static export만 dead code elimination

  • CJS require — shaking 어려움 → "sideEffects": false 한계

  • 라이브러리 배포: dual package (ESM + CJS) 또는 ESM only

  • Node 20+: ESM first, "module" field in package.json

  • TypeScript module: ESNext, moduleResolution: bundler

  • Next.js — server/client module boundary

🔗 참고 자료