पाठ 15 / 30

Output Module Formats

CommonJS, ES modules, और UMD output के बीच चुनें।

Module systems: CJS बनाम ESM

CommonJS (require, module.exports) Node.js पर हावी रहे। ES modules (import, export) आधुनिक standard हैं। Babel दोनों या दोनों को output कर सकता है।

Output format को control करना

डिफ़ॉल्ट रूप से, Babel module syntax को preserve करता है। import को require में transform करने के लिए plugins का उपयोग करें या vice versa।

// Keep ES modules (default for modern builds)
{
  "presets": ["@babel/preset-env"]
}

// Transform to CommonJS (for Node libraries)
{
  "presets": [
    ["@babel/preset-env", { "modules": "commonjs" }]
  ]
}

Libraries अक्सर CJS और ESM दोनों को ship करते हैं

npm packages अक्सर दोनों formats को शामिल करते हैं: dist/index.js (CommonJS) और dist/index.mjs (ES modules)। Bundlers और Node.js सही format को चुनते हैं।