JavaScript Module System
Modules let you split code across files, control what is public vs private, and manage dependencies. Two systems coexist: CommonJS (Node.js original) and ES Modules (the modern standard). Knowing both is essential for Node.js developers.
// ── CommonJS (CJS) — Node.js original ────────────────────────────
// math.js
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
module.exports = { add, multiply }; // named exports
// OR: module.exports = add; // default export
// main.js
const { add } = require('./math'); // destructure
const math = require('./math'); // whole object
const add2 = require('./math').add; // direct access
// Dynamic require (runtime, lazy loading)
if (condition) {
const extra = require('./optional-feature');
}
// ── ES Modules (ESM) — modern standard ───────────────────────────
// math.mjs or with "type":"module" in package.json
export function add(a, b) { return a + b; }
export const PI = 3.14159;
export default class Calculator { /* ... */ }
// main.mjs
import { add, PI } from './math.mjs'; // named imports
import Calculator from './math.mjs'; // default import
import * as math from './math.mjs'; // namespace import
import { add as sum } from './math.mjs'; // rename import
// Dynamic import (lazy, returns Promise)
const { add } = await import('./math.mjs');
button.onclick = async () => {
const { heavyFn } = await import('./heavy-module.mjs');
heavyFn();
};
CJS vs ESM Comparison
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require/exports | import/export |
| Loading | Runtime (synchronous) | Parse time (static) |
| Tree shaking | No | Yes (bundlers) |
| Top-level await | No | Yes |
| Browser native | No (bundler needed) | Yes (type=module) |
Comments (0)
No comments yet. Be the first!
Leave a Comment