Node supporta due sistemi di moduli: CommonJS (CJS) — l'originale, che utilizza require/module.exports — e ES Modules (ESM) — lo standard, che utilizza /. Si differenziano nella sintassi, nel comportamento di caricamento e nell'interoperabilità.
Node supporta due sistemi di moduli: CommonJS (CJS) — l'originale, che utilizza require/module.exports — e ES Modules (ESM) — lo standard, che utilizza /. Si differenziano nella sintassi, nel comportamento di caricamento e nell'interoperabilità.
importexport// 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
O utilizzare esplicitamente l'estensione .mjs. Senza questo, Node impostana .js su CommonJS per impostazione predefinita.
// 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");
Il punto dolente: CJS non può require() pacchetti solo ESM — un dolore comune durante la migrazione. Tenete anche presente che ESM non ha __dirname (usate import.meta.url invece).
Conoscere entrambi i sistemi è essenziale per il lavoro reale con Node: ESM è il futuro (standard, tree-shakeable, top-level await, allineato con il browser) e la scelta giusta per i nuovi progetti, ma una grande parte dell'ecosistema npm e del codice esistente è CommonJS.
Comprendere le differenze di sintassi, come abilitare ESM ("type": "module"), e i limiti di interoperabilità (specialmente CJS-non-può-richiedere-ESM) previene la confusione frequente e gli errori che sorgono quando li si mescolano.