ये फाइलों के बीच कोड विभाजित करने के लिए JavaScript के दो module सिस्टम हैं।
ES Modules (ESM) — आधुनिक मानक
// import / export, used in browsers and modern Node
import { sum } from ;
defaultThing ;
x = ;
() {};
ये फाइलों के बीच कोड विभाजित करने के लिए JavaScript के दो module सिस्टम हैं।
// import / export, used in browsers and modern Node
import { sum } from ;
defaultThing ;
x = ;
() {};
const { sum } = require("./math");
module.exports = { x: 1 };
| ES Modules | CommonJS | |
|---|---|---|
| वाक्य रचना | import/export | require/module.exports |
| लोडिंग | static, async | dynamic, synchronous |
| विश्लेषणीय | ✅ → tree-shaking | ❌ कठिन |
| बाइंडिंग | live (read-only) | कॉपी किया गया मान |
this शीर्ष पर | undefined | module.exports |
Static का मतलब है कि ESM imports पार्स समय पर ज्ञात हैं, जो bundlers को tree-shaking (अप्रयुक्त exports को छोड़ना) करने देता है। CommonJS require गतिशील है (आप शर्तपूर्वक require कर सकते हैं), इसलिए इसका आसानी से विश्लेषण नहीं किया जा सकता है।
{ "type": "module" } // in package.json, or use the .mjs extension
आप CommonJS से ESM-only package को require() नहीं कर सकते; दोनों को मिश्रित करने में कठिन किनारे हैं। ESM imports भी live bindings हैं — यदि निर्यातक मान बदलता है, तो आयातकर्ता नया मान देखते हैं (CJS आपको snapshot प्रति देता है)।
ESM भविष्य है (browser-native, tree-shakeable, top-level await)।
नए कोड के लिए इसे प्राथमिकता दें; CJS को समझें क्योंकि Node ecosystem का बड़ा हिस्सा अभी भी इसका उपयोग करता है।
विस्तृत उत्तरों के साथ IT इंटरव्यू प्रश्नों की एक लाइब्रेरी — जूनियर से सीनियर तक।
दान करें