Iki loro modul sistem JavaScript kanggo pamisah kode ing luwih-luwih file.
ES Modules (ESM) — standar modern
js
// import / export, used in browsers and modern Node
import { sum } from "./math.js";
import defaultThing from "./thing.js";
export const x = 1;
export default function () {};
CommonJS (CJS) — sistem warisan Node
js
const { sum } = require("./math");
module.exports = { x: 1 };
Bedane utama
| ES Modules | CommonJS | |
|---|---|---|
| Sintaks | import/export | require/module.exports |
| Pambukaan | static, async | dinamis, sinkron |
| Bisa dikaji | ✅ → tree-shaking | ❌ luwih angel |
| Ikatan | live (maca-mung) | nilai kopian |
this ing ndhuwur | undefined | module.exports |
Static tegese ESM imports dikenal nalika parse time, kang ngidini bundler nindakake tree-shaking (buang ekspor sing ora dienggo). require CommonJS iku dinamis (sampeyan bisa require kanthi syarat), mula ora bisa dikaji gampang.
Ngaktifake ESM ing Node
json
{ "type": "module" } // in package.json, or use the .mjs extension
Gotcha Interop
Sampeyan ora bisa require() paket ESM-only saka CommonJS; campur loro-loro duwe pinggir kasar. import ESM uga live bindings — yen ekspor ngganti nilai, importers ndelok nilai anyar (CJS ngabei sampeyan kopian snapshot).
Kenapa penting
ESM minangka masa depan (asli-browser, tree-shakeable, top-level await).
Lebih dituladha kanggo kode anyar; ngerti CJS amarga asil Node ekosistem isih nganggo iki.
