learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Modules (ESM and CommonJS)

Splitting code into files with import/export or require, and how the two systems differ.

Modules explained

Modules split JavaScript into files that import and export what they need, instead of sharing everything through global variables. There are two systems: ES modules (ESM), using import and export, the standard in browsers and modern Node.js; and CommonJS, using require and module.exports, Node.js's original system that many packages still use.

ES modules and CommonJS side by side

// ESM: math.js
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// app.js
import multiply, { add } from "./math.js";

// CommonJS: math.cjs
module.exports = { add: (a, b) => a + b };
// app.cjs
const { add } = require("./math.cjs");

Key differences

  • Static versus dynamic: ESM imports are fixed at the top of the file, so tools can analyse them and remove unused code (tree shaking). require can be called anywhere at runtime.
  • Loading: ESM loads asynchronously and supports top-level await; require is synchronous.
  • Live bindings: an ESM import is a live view of the exported variable, so later changes in the exporting module are visible. With CommonJS you get the module.exports object; values you destructure from it are plain copies that do not update.
  • In Node.js, a file is ESM if it ends in .mjs or the nearest package.json has "type": "module", and CommonJS if it ends in .cjs or has "type": "commonjs". With no marker, current Node.js versions look at the code and treat it as ESM if it uses import/export syntax. Being explicit is still clearer.
  • Interop: ES modules can import CommonJS packages. Recent Node.js versions also let require() load ES modules, as long as they do not use top-level await; otherwise use dynamic import().

Common mistakes

  • Mixing systems in one file: require, module and __dirname do not exist inside an ES module (use import and import.meta).
  • Leaving out file extensions in Node.js ESM imports, which require them for relative paths.
  • Circular imports: two modules importing each other can see half-initialised values. Move shared code into a third module.

What interviewers ask about modules

  • "ESM versus CommonJS?" Syntax, static versus dynamic loading, live bindings, tree shaking.
  • "Named or default exports?" Named exports are explicit and easier to refactor and auto-import.
  • "How do you load a module conditionally?" Dynamic import(), which returns a promise.
Concept map
Part of JavaScriptModules

What to learn after Modules

Connections to other concepts

Part of
JavaScript

Read and watch: Modules explained

Practise Modules

All topics