Typorithm · easy

CommonJS vs ESM

require-vs-importnodejscommonjsesmtype-module
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn CommonJS vs ESM

0%

Modules & npm

CommonJS uses require() and module.exports; ES Modules use import and export. Node treats .js as CommonJS unless package.json sets "type": "module" (or you use the .mjs extension).

Node ships two module systems. CommonJS (CJS) loads dependencies with require() and exposes values via module.exports; it has been Node's default since the start.

ES Modules (ESM) are the language standard: import pulls in bindings and export (default or named) exposes them. Imports are static and resolved before the file executes.

Node decides which system a .js file is by package.json: with "type": "module" it parses files as ESM, otherwise as CommonJS. The .mjs and .cjs extensions force one mode regardless.

01

CommonJS: require() / module.exports.

02

ESM: import / export default / export const.

03

"type": "module" makes .js files ESM.

// CommonJS
const fs = require("fs");
module.exports = foo;

// ES Modules
import fs from "fs";
export default foo;
export const x = 1;

Read the implementation

Connect each part of the code to the concept before you type.

1. CommonJS import

require() synchronously loads a module and returns its exports — the CommonJS way.

const fs = require("fs");

2. CommonJS export

module.exports assigns what require() will return from this file.

module.exports = foo;

3. ESM import

import is the static, standard ES Modules syntax, resolved before the module runs.

import fs from "fs";

4. ESM default export

export default declares the single main value a module exposes.

export default foo;

5. ESM named export

export const declares a named binding importers pull in by name.

export const x = 1;

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

CommonJS vs ESM: Lesson & Practice · Typorithm | ApplyDjinn