Node ndhukung rong sistem modul: CommonJS (CJS) — sing asli, nganggo require/module.exports — lan ES Modules (ESM) — standar, nganggo import/. Beda ing sintaks, tingkah laku pemuatan, lan interoperabilitas.
Node ndhukung rong sistem modul: CommonJS (CJS) — sing asli, nganggo require/module.exports — lan ES Modules (ESM) — standar, nganggo import/. Beda ing sintaks, tingkah laku pemuatan, lan interoperabilitas.
export// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require("./math"); // synchronous, runtime
// math.mjs (or .js with "type": "module")
export function add(a, b) { return a + b; }
export default something;
// app.mjs
import { add } from "./math.mjs"; // static, hoisted
CommonJS ES Modules
Syntax require/module.exports import/export
Loading synchronous, runtime static, hoisted
Top-level await no yes
Tree-shaking hard yes (statically analyzable)
File extension .cjs / .js (default) .mjs / .js with "type":"module"
__dirname/__filename available not available (use import.meta.url)
// package.json
{ "type": "module" } // now .js files are treated as ESM
Utawa nganggo ekstensyon .mjs kanthi jelas. Tanpa iki, Node ngatur .js menyang CommonJS sacara default.
// ESM can import CommonJS:
import pkg from "some-cjs-lib"; // works (default import)
// CommonJS CANNOT require() a pure-ESM package (it's async):
const esm = require("esm-only-pkg"); // ❌ ERR_REQUIRE_ESM
// must use dynamic import: const esm = await import("esm-only-pkg");
Pinge telak: CJS ora bisa require() paket ESM-only — masalah migrasi sing umum. Uga diperhatian manawa ESM ora duwe __dirname (nganggo import.meta.url sabalihe).
Ngerti rong sistem penting banget kanggo karya Node nyata: ESM yaiku masa depan (standar, tree-shakeable, top-level await, selaras karo browser) lan pilihan sing tepat kanggo proyek anyar, nanging sampeyan banyak ekosistem npm lan kode sing ana yaiku CommonJS.
Mahami bedane sintaks, carane ngaktifkan ESM ("type": "module"), lan watesan interoperabilitas (khususé CJS-ora-bisa-require-ESM) nyegah kebingungan lan kesalahan sing kerep tuwuh nalika ngampur-ampur.