📡 You're offline — showing cached content
New version available!
Quick Access
PHP Intermediate

JavaScript Module System: ESM vs CommonJS Explained

Understand JavaScript modules — CommonJS require/exports vs ES Modules import/export, static vs dynamic loading, and tree shaking.

EzyCoders Admin November 11, 2025 10 min read 0 views
JavaScript Module System ESM CommonJS Guide
Share: Twitter LinkedIn WhatsApp

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

FeatureCommonJSES Modules
Syntaxrequire/exportsimport/export
LoadingRuntime (synchronous)Parse time (static)
Tree shakingNoYes (bundlers)
Top-level awaitNoYes
Browser nativeNo (bundler needed)Yes (type=module)
EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment