기본 패턴
javascript
// CommonJS
const utils = require("./utils");
module.exports = {
format,
};
// ES Module
import { format } from "./utils.js";
export { format };설명
- Node.js는 기본 CommonJS이며
.mjs또는package.json에서type: "module"을 쓰면 ES 모듈을 인식합니다. module.exports = { ... }은 하나의 객체로 내보내고,exports.default도 가능합니다.require/import는 상대 경로 뒤에 확장자를 맞춰야 하고, 캐시는 처음 한 번만 초기화됩니다.
짧은 예제
javascript
// helpers.js
exports.capitalize = (value) => value[0].toUpperCase() + value.slice(1);
// index.js
const { capitalize } = require("./helpers");
console.log(capitalize("hello"));빠른 정리
| 방식 | 특징 |
|---|---|
| CommonJS | require, module.exports |
| ES Module | import, export |
package.json | "type": "module" 로 ES 모듈 활성화 |
주의할 점
두 모듈 타입을 혼합하면 import/require 오류가 나므로, 프로젝트 전체에서 하나를 기준으로 잡고 babel/tsc로 트랜스파일하는 것이 안전합니다.