Modules (ES Modules & CommonJS)

📖 Concept

Modules let you split code into separate files, each with its own scope. They prevent global namespace pollution and make code reusable, maintainable, and testable.

ES Modules (ESM) — The modern standard. Uses import/export. Static (analyzed at compile time). Supported in browsers and Node.js. CommonJS (CJS) — Node.js's original module system. Uses require()/module.exports. Dynamic (evaluated at runtime).

🏠 Real-world analogy: Modules are like departments in a company. Each department (file) has its own resources and can share specific services (exports) with other departments (imports).

💻 Code Example

codeTap to expand ⛶
1// ===== ES Modules (ESM) =====
2
3// math.js — Named exports
4export const PI = 3.14159;
5export function add(a, b) { return a + b; }
6export function multiply(a, b) { return a * b; }
7
8// user.js — Default export
9export default class User {
10 constructor(name) { this.name = name; }
11}
12
13// app.js — Importing
14import User from "./user.js"; // Default import
15import { add, multiply } from "./math.js"; // Named imports
16import { add as sum } from "./math.js"; // Renamed import
17import * as MathUtils from "./math.js"; // Namespace import
18
19// Re-exporting
20export { add, multiply } from "./math.js";
21export { default as User } from "./user.js";
22
23// Dynamic import (code splitting)
24async function loadChart() {
25 const { Chart } = await import("./chart.js");
26 return new Chart();
27}
28
29// ===== CommonJS (CJS) =====
30
31// math.js
32// module.exports = { add, multiply };
33// or
34// exports.add = (a, b) => a + b;
35
36// app.js
37// const { add, multiply } = require("./math");
38// const math = require("./math");

🏋️ Practice Exercise

Mini Exercise:

  1. Create a utility module with 5+ exported functions
  2. Create a module with both named and default exports
  3. Use dynamic import() to lazy-load a module on button click
  4. Convert a CommonJS module to ES Module syntax

⚠️ Common Mistakes

  • Mixing ESM and CJS in the same file — they are incompatible syntax

  • Forgetting to add type: 'module' in package.json or use .mjs extension for ESM in Node.js

  • Circular imports causing undefined values — restructure code to avoid circular dependencies

  • Using require() in browser without a bundler — browsers only support import/export

  • Not knowing that import statements are hoisted and run before any code in the file

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Modules (ES Modules & CommonJS). Login to unlock this feature.