Tooling & Build

Module Formats

JavaScript has had many module systems: IIFE, AMD, CJS, UMD, and ESM. Today ES Modules (ESM) is the standard, but understanding all formats is essential for working with Node.js, publishing libraries, and debugging interop issues.

What is the difference between CommonJS and ES modules?

CommonJS is Node.js's original module system: require() to import and module.exports to export, loaded synchronously. ES modules (ESM) are the official JavaScript standard: import/export, statically analysable, supported by browsers and modern Node. New code should use ESM; you'll still meet CommonJS in older packages.

// CommonJS
const fs = require("fs");
module.exports = { read };

// ES modules
import fs from "node:fs";
export function read() { … }

Evolution of Module Formats

~2005
IIFE
Immediately Invoked Function Expression — wraps code in a function to create a private scope
Legacy code only
2009
CJS
CommonJS — created for Node.js server-side. require() / module.exports. Still dominant in Node.
Node.js default (legacy)
2011
AMD
Asynchronous Module Definition (RequireJS) — async loading in browsers before ESM existed
Mostly obsolete
2014
UMD
Universal Module Definition — works as CJS + AMD + browser global. Used for library bundles.
Library bundles
2015
ESM
ES Modules — official JS standard. import/export. Static analysis, tree-shakeable, async-capable.
✅ The standard today

Common Pitfalls

Mixing require() and import in the same file — causes SyntaxError in Node.js or bundler errors
Pick one system per file. Use ESM (import/export) for new code. CJS for legacy Node.js scripts.
Forgetting 'type': 'module' in package.json when using .js extension for ESM — Node treats .js as CJS by default
Add '"type": "module"' to package.json, or use .mjs extension for ESM files.
Publishing a library as CJS only — ESM consumers can't tree-shake it, bundle sizes increase
Publish dual builds: both CJS (.cjs) and ESM (.mjs) using package.json 'exports' field.
Using import() dynamic import and forgetting it returns a Promise — causes TypeError
Always await dynamic imports: 'const { fn } = await import("./mod.js")'

Module Formats Demo

Code Editor

<div class="cols">
<pre>// CommonJS (Node.js, older)
const { add } = require("./math");
module.exports = { add };</pre>
<pre>// ES modules (standard)
import {
  add,
} from "./math.js";
export function add(a, b) { return a + b; }</pre>
</div>
<p id="out"></p>

Preview

CommonJS vs ES Modules: summary

Key points

  • In Node.js, .mjs files or "type": "module" in package.json enable ESM.
  • ESM can import CommonJS, but CommonJS needs dynamic import() to load ESM in many cases.
  • Bundlers can only tree-shake ES modules.

Frequently asked questions

›Why do I get "require is not defined"?

You're in an ES module context, such as the browser or a "type": "module" package. Use import instead of require.