# ES Modules vs CommonJS

> What is the difference between ES Modules and CommonJS? When would you use each?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-modules-advanced
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is the difference between ES Modules and CommonJS? When would you use each?

## Answer

CommonJS (CJS):

- Used in Node.js historically
- require() is synchronous and dynamic
- module.exports and exports object
- Loaded at runtime

ES Modules (ESM):

- Native browser module standard and modern Node.js
- import/export syntax
- Static analysis - imports resolved at parse time
- Async loading
- Enables tree shaking

Key differences:

- ESM is static; CJS is dynamic (require() inside conditions works)
- ESM has live bindings; CJS exports values by copy
- ESM has top-level await; CJS does not
- Node.js requires .mjs or type: module in package.json for ESM

**Parse, link, evaluate: ES modules. Switch to CommonJS under Tweak and compare.**

1. **Static imports**: The whole module graph is found before any code runs.
2. **Linking**: Imported names become live bindings to the exporter's variables.
3. **Dependencies evaluate first**: counter.js runs before main.js, even though the log comes first in the source.
4. **Output**: counter loaded, main start, 1.

## Code examples

### ESM vs CJS Syntax and Live Bindings

```
// CommonJS
const { readFile } = require('fs').promises;
module.exports = { greet: (name) => `Hello ${name}` };

// Dynamic require (only possible in CJS)
if (process.env.NODE_ENV === 'test') {
  const mock = require('./mocks');
}

// ES Modules
import { readFile } from 'fs/promises';
export const greet = (name) => `Hello ${name}`;
export default function main() {}

// Named vs default
import defaultExport from './module';
import { named } from './module';
import * as all from './module';

// Dynamic import (lazy loading)
const { heavy } = await import('./heavy-module.js');

// Top-level await (ESM only)
const config = await fetch('/config.json').then(r => r.json());
console.log(config.version);
```

ESM exports are live bindings - imported values reflect changes. CJS exports are copied values. Dynamic import() enables code splitting.

### Tree Shaking

```
// utils.js with named exports (tree-shakeable)
export function formatDate(date) { return date.toISOString(); }
export function formatCurrency(n) { return `$${n.toFixed(2)}`; }
export function parseQuery(str) { /* ... */ }

// Only formatDate imported - bundler eliminates others
import { formatDate } from './utils.js';

// Dynamic import for code splitting
document.querySelector('#loadChart').addEventListener('click', async () => {
  const { Chart } = await import('./chart.js');
  new Chart(document.querySelector('#canvas')).render(data);
});

// Check if in ESM vs CJS (Node.js)
const isESM = typeof __dirname === 'undefined';
const currentDir = isESM
  ? new URL('.', import.meta.url).pathname
  : __dirname;
```

Named exports are tree-shakeable - bundlers eliminate unused code statically. Dynamic import() enables route-level code splitting.

## Key points

- Node.js supports ESM via .mjs files or 'type': 'module' in package.json
- Top-level await is only available in ESM (not CJS)
- import.meta.url gives the current module URL in ESM (replaces \__filename)
- Default exports are less tree-shakeable - prefer named exports in libraries

## Common follow-up questions

- What is tree shaking and why does it require ES Modules?
- What is the difference between a live binding and a value copy?
- How does top-level await work in ESM?

## Interview tips

- Lead with the static vs dynamic distinction - it enables tree shaking
- Live bindings are a common gotcha - know the difference from CJS copies
- Dynamic import() for code splitting shows practical performance awareness

## Concepts covered

ES Modules, CommonJS, import, require, Tree Shaking, Dynamic Import

Previous: [Advanced Object Patterns and Mixins](https://www.internhack.in/learn/interview/javascript-interview/js-object-patterns) · Next: [Promise Combinators](https://www.internhack.in/learn/interview/javascript-interview/js-promise-combinators) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Variables: var, let, const](https://www.internhack.in/learn/interview/javascript-interview/js-var-let-const)
- [Data Types & Type Checking](https://www.internhack.in/learn/interview/javascript-interview/js-data-types)
- [Operators & Short-Circuit Evaluation](https://www.internhack.in/learn/interview/javascript-interview/js-operators-short-circuit)
- [String Methods & Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-string-methods)
- [Array Methods (map, filter, reduce)](https://www.internhack.in/learn/interview/javascript-interview/js-array-methods)
- [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
