Module Systems
CommonJS vs ES Modules
Understand how JavaScript organizes code into reusable, isolated pieces and why the two major module systems differ.
What Is a Module?
A module is a self-contained file of JavaScript code that exports specific values (functions, objects, variables) and can import values from other modules. Instead of dumping everything into one giant file, modules let you split your program into focused, reusable pieces.
Why Modules Matter
The Two Major Systems
JavaScript has two dominant module systems that you will encounter in nearly every project. They solve the same problem but use different syntax and work in different ways.
CommonJS Syntax
// Exporting from a module const PI = 3.14159; function add(a, b) { return a + b; } module.exports = { PI, add };
// Importing from a module const { PI, add } = require('./math'); console.log(add(2, 3)); // 5 console.log(PI); // 3.14159
ES Modules Syntax
// Named exports export const PI = 3.14159; export function add(a, b) { return a + b; }
// Named imports import { PI, add } from './math.mjs'; console.log(add(2, 3)); // 5 console.log(PI); // 3.14159
How Loading Differs
Static vs Dynamic Loading
// CommonJS: conditional, dynamic if (needsFeature) { const feature = require('./feature'); } // ES Modules: this is a syntax error! // if (needsFeature) { import { x } from './feature'; }
Named vs Default Exports
export const PI = 3.14; export function add(a, b) { return a + b; } // Import with exact names: import { PI, add } from './math.mjs';
export default function add(a, b) { return a + b; } // Import with any name you choose: import myAdd from './math.mjs';
How to Choose a Module System
package.json. If "type": "module" is set, Node treats .js files as ES Modules. Otherwise, it treats them as CommonJS..mjs forces ES Module mode; .cjs forces CommonJS mode, regardless of package.json.Example: Creating a Utility Module
export function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } export function reverse(str) { return str.split('').reverse().join(''); }
import { capitalize } from './stringUtils.mjs'; console.log(capitalize('hello')); // "Hello"
Example: Re-exporting a Barrel File
A barrel file collects exports from multiple modules into one convenient entry point. This is a common pattern in larger projects.
export { capitalize, reverse } from './stringUtils.mjs'; export { add, multiply } from './math.mjs'; export { default as Logger } from './logger.mjs';
// One clean import from the barrel import { capitalize, add, Logger } from './index.mjs';
Example: Dynamic import()
ES Modules also support dynamic import(): a function-like syntax that returns a Promise. This bridges the gap with CommonJS's flexibility.
// Load a module only when the user clicks button.addEventListener('click', async () => { const { chart } = await import('./chart.mjs'); chart.render(); });
The Dependency Graph
Common Mistakes
'./math.mjs'). CommonJS can omit it. Forgetting the extension breaks ESM imports.import add from './math' when the module uses named exports returns undefined. Use curly braces: import { add }.Side-by-Side Comparison
| CommonJS | ES Modules | |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| Loading | Synchronous | Asynchronous |
| Analysis | Dynamic (runtime) | Static (compile time) |
| Tree-shaking | Not possible | Supported |
| Conditional Import | Direct (in if block) | Via dynamic import() |
| Default in Node | Yes (legacy) | With "type":"module" |
| Browser Support | Needs bundler | Native |
Question 1 of 5
Which syntax is used to export a value from a CommonJS module?
Question 2 of 5
What is the main advantage of ES Modules being statically analyzed?
Question 3 of 5
A developer writes this code in an ES Module file. What happens?
if (needsChart) { import { render } from './chart.mjs'; }
Question 4 of 5
A module has the following exports. How would you import only the greet function?
// helpers.mjs export function greet(name) { return `Hello, ${name}`; } export function farewell(name) { return `Bye, ${name}`; }
import { greet }. Option A (without braces) attempts to import a default export, which does not exist here. Option B uses CommonJS syntax.Question 5 of 5
In Node.js, how do you tell the runtime to treat .js files as ES Modules instead of CommonJS?
.js files as ES Modules. Without it, Node defaults to CommonJS. Alternatively, use .mjs extensions for individual files.