๋ฐ์ํ
๋ชจ๋ ์์คํ
์ฝ๋๋ฅผ ํ์ผ ๋จ์๋ก ๋๋ ์ ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ. JavaScript์๋ ๋ ๊ฐ์ง ๋ฐฉ์์ด ์๋ค.
CommonJS (CJS)
Node.js ๊ธฐ๋ณธ ๋ฐฉ์. require / module.exports ์ฌ์ฉ.
// math.js
function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
module.exports = { add, sub };
// app.js
const { add, sub } = require("./math");
console.log(add(1, 2)); // 3
ESM (ES Modules) โ ์ต์ ๋ฐฉ์
๋ธ๋ผ์ฐ์ /Node.js ๋ชจ๋ ์ง์. import / export ์ฌ์ฉ.
// math.js
export function add(a, b) { return a + b; }
export function sub(a, b) { return a - b; }
// app.js
import { add, sub } from "./math.js";
console.log(add(1, 2)); // 3
์ฐจ์ด์
| ๊ตฌ๋ถ | CommonJS | ESM |
|---|---|---|
| ๋ฌธ๋ฒ | require / module.exports |
import / export |
| ์คํ | ๋๊ธฐ (๋ฐํ์์ ๋ก๋) | ๋น๋๊ธฐ (์ ์ ๋ถ์) |
| ํ๊ฒฝ | Node.js ๊ธฐ๋ณธ | ๋ธ๋ผ์ฐ์ + Node.js |
| ํ์ฅ์ | .js |
.mjs ๋๋ "type": "module" |
์์ด ์ฐ๋ฉด ์๋ฌ๋๋ค.
default export vs named export
// named export โ ์ฌ๋ฌ ๊ฐ ๋ด๋ณด๋ด๊ธฐ
export function add() {}
export function sub() {}
import { add, sub } from "./math.js"; // ์ด๋ฆ ๊ทธ๋๋ก ์จ์ผ ํจ
// default export โ ํ๋๋ง ๋ด๋ณด๋ด๊ธฐ
export default function add() {}
import add from "./math.js"; // ์ค๊ดํธ ์์
import myAdd from "./math.js"; // ์ด๋ฆ ๋ง์๋๋ก ๋ฐ๊ฟ๋ ๋จ
// ๋์์ ์ฌ์ฉ
import circle, { PI } from "./utils.js";
์ค๋ฌด์์ ํ์ฌ vs ์์ผ๋ก
// ํ์ฌ ํ์ฌ (CommonJS)
const express = require("express");
const db = require("../config/db");
// TypeScript / ์ต์ ํ๋ก์ ํธ (ESM)
import express from "express";
import db from "../config/db";
๋ฉด์ ๋ต๋ณ
"CommonJS๋ Node.js ๊ธฐ๋ณธ ๋ฐฉ์์ผ๋ก require/module.exports๋ฅผ ์ฌ์ฉํ๊ณ ๋๊ธฐ์ ์ผ๋ก ๋ก๋๋ฉ๋๋ค. ESM์ ์ต์ ํ์ค์ผ๋ก import/export๋ฅผ ์ฌ์ฉํ๋ฉฐ ์ ์ ๋ถ์์ด ๊ฐ๋ฅํฉ๋๋ค. ๋ ๋ฐฉ์์ ์์ด ์ธ ์ ์๊ณ , TypeScript๋ ์ต์ ํ๋ก์ ํธ์์๋ ESM์ ์ฃผ๋ก ์ฌ์ฉํฉ๋๋ค."
๋ฐ์ํ