01 / 21

Module Systems
CommonJS vs ES Modules

Understand how JavaScript organizes code into reusable, isolated pieces and why the two major module systems differ.

JavaScript

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.

math.js add() multiply() PI imports app.js uses add() uses PI imports utils.js format() log()

Why Modules Matter

Encapsulation
Each module has its own scope. Internal variables stay private unless explicitly exported.
Reusability
Write a function once, import it everywhere. No copy-pasting code between files.
Maintainability
Smaller, focused files are easier to debug, test, and update than one monolithic script.

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 (CJS)
The original Node.js module system. Uses require() and module.exports. Loads modules synchronously at runtime.
ES Modules (ESM)
The official JavaScript standard since ES2015. Uses import and export keywords. Designed for static analysis and async loading.

CommonJS Syntax

math.js
// Exporting from a module
const PI = 3.14159;

function add(a, b) {
  return a + b;
}

module.exports = { PI, add };
app.js
// Importing from a module
const { PI, add } = require('./math');

console.log(add(2, 3)); // 5
console.log(PI);          // 3.14159

ES Modules Syntax

math.mjs
// Named exports
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}
app.mjs
// Named imports
import { PI, add } from './math.mjs';

console.log(add(2, 3)); // 5
console.log(PI);          // 3.14159

How Loading Differs

CommonJS 1. Encounter require() 2. PAUSE: load + execute file 3. Return exports object 4. Continue execution SYNCHRONOUS ES Modules 1. Parse all imports (static) 2. Build dependency graph 3. Fetch + link modules 4. Evaluate in order ASYNCHRONOUS

Static vs Dynamic Loading

Static (ES Modules)
Imports are analyzed before the code runs. The engine knows the full dependency tree at compile time. This enables tree-shaking: removing unused exports from your final bundle.
Dynamic (CommonJS)
Imports happen during execution. You can compute the module path in a variable. This is flexible but means bundlers cannot reliably detect unused code.
Dynamic require
// 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

Named exports (ESM)
export const PI = 3.14;
export function add(a, b) { return a + b; }

// Import with exact names:
import { PI, add } from './math.mjs';
Default export (ESM)
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

1
Check the environment. Is the code running in Node.js or the browser? Node historically uses CommonJS; browsers use ES Modules.
2
Check package.json. If "type": "module" is set, Node treats .js files as ES Modules. Otherwise, it treats them as CommonJS.
3
Look at file extensions. .mjs forces ES Module mode; .cjs forces CommonJS mode, regardless of package.json.
4
Prefer ES Modules for new code. ESM is the official standard, enables tree-shaking, and works in both browsers and modern Node.js.

Example: Creating a Utility Module

stringUtils.mjs
export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function reverse(str) {
  return str.split('').reverse().join('');
}
app.mjs
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.

index.mjs (barrel)
export { capitalize, reverse } from './stringUtils.mjs';
export { add, multiply } from './math.mjs';
export { default as Logger } from './logger.mjs';
consumer.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.

ESM dynamic import
// Load a module only when the user clicks
button.addEventListener('click', async () => {
  const { chart } = await import('./chart.mjs');
  chart.render();
});

The Dependency Graph

main.mjs auth.mjs api.mjs utils.mjs Shared dependency: loaded once, referenced by both

Common Mistakes

✕ Mixing Systems
Using require() inside an ES Module file (or vice versa) without understanding how they interop. This causes runtime errors.
✕ Missing File Extension
ES Modules in Node require the full path with extension (e.g., './math.mjs'). CommonJS can omit it. Forgetting the extension breaks ESM imports.
✕ Default vs Named Confusion
Writing 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}`; }

Question 5 of 5

In Node.js, how do you tell the runtime to treat .js files as ES Modules instead of CommonJS?