Lesson 73 of 296
Modules: ES modules vs CommonJS
What you will learn
- What a module is and why modules matter
- ES modules:
importandexport - Named and default exports
- CommonJS:
requireandmodule.exports - The differences between the two systems
- Using modules in the browser and in Node.js
- Dynamic imports and tree shaking
On this page
What is a module?
A module is a file that keeps its code private by default and chooses what to share with other files. Modules let you split a big program into small files with clear jobs.
Benefits:
- No global variables leaking between files.
- Clear dependencies: each file says exactly what it uses.
- Reusable code.
ES modules (ESM): the standard
ES modules are the official JavaScript module system, built into browsers and Node.js.
Named exports: a file can export many things by name.
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}// app.js
import { add, PI } from "./math.js";
import { multiply as times } from "./math.js"; rename on import
import * as math from "./math.js"; everything as one object
math.add(1, 2);Names must match exactly, inside curly braces.
Default export: one main thing per file.
// logger.js
export default function log(message) {
console.log(`[LOG] ${message}`);
}import log from "./logger.js"; no braces; you choose the name
import writeLog from "./logger.js"; also worksBoth in one file:
import React, { useState } from "react";Named or default? Many teams prefer named exports: names stay the same everywhere, editors auto-import them reliably, and renaming is easier. Some frameworks require default exports for certain files (for example, Next.js page files).
Re-exporting (common in index.js files):
export { add, multiply } from "./math.js";Using ESM in the browser
<script type="module" src="/js/app.js"></script>Module scripts are deferred automatically and run in strict mode.
CommonJS (CJS): Node.js's original system
Before ES modules existed, Node.js created CommonJS. You will see it in many Node.js projects and packages.
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };// app.js
const { add } = require("./math");ESM vs CommonJS
| ES modules | CommonJS | |
|---|---|---|
| Syntax | import / export | require() / module.exports |
| Standard | Official JavaScript standard | Created by Node.js |
| Where | Browsers and Node.js | Node.js (and bundlers) |
| Loading | Static: imports are known before the code runs | Dynamic: require is a normal function call, run at that line |
| Imports must be at the top level | Yes (except import()) | No, require can be anywhere |
| Top-level await | Yes | No |
| Strict mode | Always | Only if you add "use strict" |
| Imported values | Live bindings: you see updates the exporting module makes | A copy of what was exported at that moment |
| File extension needed in imports (Node.js) | Yes, usually: ./math.js | No: ./math works |
Choosing the system in Node.js
- Add
"type": "module"topackage.jsonto make.jsfiles ES modules. - Without it,
.jsfiles are CommonJS. .mjsfiles are always ESM;.cjsfiles are always CommonJS.
For new projects, use ES modules. Mixing the two has rules: ESM can import CommonJS packages, and recent versions of Node.js can also require() many ES modules, but older versions cannot. TypeScript projects add their own settings on top (Part 9).
Dynamic import()
import() loads a module when needed, and returns a promise:
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js");
openEditor();
});The editor code is only downloaded when the user clicks. This is called code splitting and makes the first page load faster. React and Next.js use it for lazy loading (Part 12).
Tree shaking
Because ES module imports are static, build tools (bundlers such as Vite, webpack or esbuild) can see exactly which exports are used, and remove unused code from the final bundle. This is called tree shaking. It works much less well with CommonJS.
Circular imports
If a.js imports b.js and b.js imports a.js, one of them may see the other's values before they are ready (undefined, or a TDZ error). If you see strange undefined imports, check for circular dependencies and move shared code to a third file.
Common mistakes
- Using braces for a default import, or no braces for a named one.
- Mixing
requireandimportin the same file without understanding the setup. - Forgetting the
.jsextension in Node.js ES modules. - Forgetting
type="module"in the browser.
How to say it in an interview
"Modules keep code private by default and share it through exports. ES modules use import and export, are the official standard in browsers and Node.js, are statically analysable, which enables tree shaking, run in strict mode, support top-level await and give live bindings. CommonJS uses require and module.exports, loads synchronously at runtime and was Node's original system. In Node, package.json type module or the .mjs and .cjs extensions decide which is used. I use dynamic import for code splitting, and prefer named exports for consistency."
Key words
| Word | Meaning |
|---|---|
| Module | A file with its own scope that exports what it shares |
| ES modules (ESM) | The standard import/export system |
| CommonJS (CJS) | Node.js's original require system |
| Named export | Exported by name; imported with braces |
| Default export | The one main export of a file |
| Dynamic import | import(), loading a module on demand |
| Bundler | A tool that combines modules into files for the browser |
| Tree shaking | Removing unused exports from the final bundle |
| Code splitting | Loading parts of the code only when needed |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.