13. ES Modules vs CommonJS: Understanding Module Systems
JavaScript has two main module systems: ES Modules (ESM) and CommonJS (CJS). This module covers the differences between them and their impact on bundling. Understanding module systems is essential for modern JavaScript development.
The key insight is that ES modules are statically analyzable, while CommonJS is dynamic. This affects tree shaking, bundling, and performance. Understanding these differences is essential for making informed decisions about module usage.
This module covers ESM vs CJS, mixing them, and bundling considerations.
ES Modules (ESM)
ES Modules are the standard JavaScript module system. They use import and export statements. ESM is statically analyzable, enabling tree shaking and other optimizations. ESM is supported in all modern browsers and Node.js (with type: module).
ESM features: static analysis, named exports, default exports, import.meta, top-level await, and strict mode by default. ESM is the future of JavaScript modules.
CommonJS (CJS)
CommonJS is the module system used by Node.js. It uses require and module.exports. CJS is dynamic, making it harder to optimize. CJS is still widely used in Node.js and many npm packages.
CJS features: require at runtime, dynamic imports, module.exports, and exports. CJS is synchronous and works well for server-side code.
// ES Modules (ESM) // math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; // app.js import { add, subtract } from './math.js'; console.log(add(2, 3)); // Default export export default function multiply(a, b) { return a * b; } // CommonJS (CJS) // math.js module.exports = { add: (a, b) => a + b, subtract: (a, b) => a - b, }; // app.js const math = require('./math.js'); console.log(math.add(2, 3)); // Using both in package.json { "type": "module" // Enables ESM for .js files } // Importing CJS in ESM import fs from 'fs'; const data = fs.readFileSync('file.txt'); // Importing ESM in CJS import('lodash-es').then(lodash => { console.log(lodash.debounce); }); // Bundling considerations // Webpack resolves .js extensions in this order: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'], }
Try It Yourself: Module Systems
Follow these steps to understand module systems.
Step 1: Create an ESM project// package.json<br>{<strong><code>type: module}
Step 2: Create a CJS project// package.json<br>{<strong><code>type: commonjs}
Step 3: Try mixing them
Import a CJS module in an ESM project. Import an ESM module in a CJS project.
Step 4: Compare bundling
Bundle ESM and CJS code separately. Compare the results.
Try It Yourself: Write a module that works in both ESM and CJS. Test it in both environments.
Knowledge Check
Ready to test your understanding of 13. ES Modules vs CommonJS: Understanding Module Systems?