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-only पैकेज को require() नहीं कर सकता — एक सामान्य माइग्रेशन समस्या। साथ ही ध्यान दें कि ESM में __dirname नहीं है (बजाय import.meta.url का उपयोग करें)।
दोनों सिस्टम को जानना वास्तविक Node कार्य के लिए आवश्यक है: ESM भविष्य है (स्टैंडर्ड, tree-shakeable, top-level await, ब्राउज़र-संरेखित) और नई परियोजनाओं के लिए सही विकल्प है, लेकिन npm इकोसिस्टम और मौजूदा कोड का एक विशाल हिस्सा CommonJS है।
सिंटैक्स अंतर, ESM को कैसे सक्षम करें ("type": "module"), और इंटरऑप सीमाओं को समझना (विशेष रूप से CJS-can't-require-ESM) उस बार-बार आने वाली भ्रामकता और त्रुटियों को रोकता है जो उन्हें मिलाते समय उत्पन्न होती है।