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
1// ===== ES Modules (ESM) =====23// math.js — Named exports4export const PI = 3.14159;5export function add(a, b) { return a + b; }6export function multiply(a, b) { return a * b; }78// user.js — Default export9export default class User {10 constructor(name) { this.name = name; }11}1213// app.js — Importing14import User from "./user.js"; // Default import15import { add, multiply } from "./math.js"; // Named imports16import { add as sum } from "./math.js"; // Renamed import17import * as MathUtils from "./math.js"; // Namespace import1819// Re-exporting20export { add, multiply } from "./math.js";21export { default as User } from "./user.js";2223// Dynamic import (code splitting)24async function loadChart() {25 const { Chart } = await import("./chart.js");26 return new Chart();27}2829// ===== CommonJS (CJS) =====3031// math.js32// module.exports = { add, multiply };33// or34// exports.add = (a, b) => a + b;3536// app.js37// const { add, multiply } = require("./math");38// const math = require("./math");
🏋️ Practice Exercise
Mini Exercise:
- Create a utility module with 5+ exported functions
- Create a module with both named and default exports
- Use dynamic
import()to lazy-load a module on button click - 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.mjsextension for ESM in Node.jsCircular imports causing
undefinedvalues — restructure code to avoid circular dependenciesUsing
require()in browser without a bundler — browsers only supportimport/exportNot knowing that
importstatements 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.