Node બે મોડ્યુલ સિસ્ટેમ્સ ને સમર્થન આપે છે: CommonJS (CJS) — મૂળ, require/module.exports નો ઉપયોગ કરીને — અને ES Modules (ESM) — ધોરણ, import/ નો ઉપયોગ કરીને. તેઓ વાક્યરચનામાં, લોડિંગ વર્તણુકમાં, અને આંતરક્રિયા માટે તફાવત ધરાવે છે.
Node બે મોડ્યુલ સિસ્ટેમ્સ ને સમર્થન આપે છે: CommonJS (CJS) — મૂળ, require/module.exports નો ઉપયોગ કરીને — અને ES Modules (ESM) — ધોરણ, import/ નો ઉપયોગ કરીને. તેઓ વાક્યરચનામાં, લોડિંગ વર્તણુકમાં, અને આંતરક્રિયા માટે તફાવત ધરાવે છે.
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
અથવા સ્પષ્ટ રીતે .mjs એક્સટેન્શન નો ઉપયોગ કરો. આ વગર, Node ડિફોલ્ટ રીતે .js ને CommonJS તરીકે ગણે છે.
// 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");
ખરબચડો ધાર: CJS ESM-માત્ર પેકેજ require() કરી શકતું નથી — આ એક સામાન્ય સ્થાનાંતર પીડા છે. એ પણ નોંધો કે ESM પાસે __dirname નથી (import.meta.url નો ઉપયોગ કરો).
બંને સિસ્ટેમ્સ જાણવું વાસ્તવિક Node કાર્ય માટે જરૂરી છે: ESM ભવિષ્ય છે (ધોરણ, tree-shakeable, top-level await, બ્રાઉઝર-સંરેખિત) અને નવી પ્રોજેક્ટ્સ માટે સાચો પસંદગી છે, પરંતુ npm ઇકોસિસ્ટમ અને હાલના કોડનો વિશાળ ભાગ CommonJS છે.
વાક્યરચનાના તફાવતો, ESM કેવી રીતે સક્ષમ કરવું ("type": "module"), અને આંતરક્રિયા મર્યાદાઓ (ખાસ કરીને CJS ESM આવશ્યક કરી શકતું નથી) સમજવું તે સામાન્ય મૂંઝવણ અને ભૂલો જે તેમને મિશ્રિત કરતી વખતે થાય છે તે રોકે છે.