Node.js supports two module systems:
- ESM (ECMAScript Modules):
import/export - CommonJS:
require()/module.exports
The extension you choose (.mjs, .cjs, or .js) decides which module system Node uses—sometimes with help from package.json.
The short rules
.mjs = always ESM
Use when you want ESM regardless of project config.
// file.mjs
import fs from "node:fs";
export const answer = 42;
.cjs = always CommonJS
Use when you want CommonJS regardless of project config.
// file.cjs
const fs = require("node:fs");
module.exports = { answer: 42 };
.js = depends on package.json
Node decides based on the closest package.json (walking up folders):
"type": "module"→.jsis treated as ESM"type": "commonjs"(or missing"type") →.jsis treated as CommonJS
// package.json
{ "type": "module" }
When to use each (practical guidance)
- Use
.jsfor most app code, and set"type"once at the package level. - Use
.mjsfor one-off ESM scripts inside a CommonJS repo (or when tooling forces it). - Use
.cjsfor config files or scripts that must stay CommonJS (some older tools/plugins).
Common pitfalls (and fixes)
1) “require is not defined” (you’re in ESM)
If Node treats the file as ESM, require() won’t exist.
Fix options:
- Convert to ESM imports, or
- Rename file to
.cjs, or - Use
createRequire:
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const pkg = require("./package.json");
2) “Cannot use import statement outside a module” (you’re in CJS)
Node treated your .js file as CommonJS.
Fix options:
- Add
"type": "module"to the nearestpackage.json, or - Rename the file to
.mjs, or - Use dynamic import from CJS:
// file.cjs
const mod = await import("./esm-module.mjs");
3) Publishing packages: support both ESM + CJS
If you publish a library, many consumers still expect both module systems.
Typical approach:
- Build two outputs (ESM + CJS)
- Use
exportsinpackage.jsonto point to each:
{
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}
A quick decision table
| You want… | Use |
|---|---|
Modern Node app with import/export everywhere | "type": "module" + .js |
| A single ESM file inside a CJS project | .mjs |
| A single CJS file inside an ESM project | .cjs |
| Maximum compatibility for published packages | dual build + exports |
Takeaway
Think of .mjs and .cjs as explicit switches, and .js as “inherit the project’s module type”. Pick one strategy per repo (usually ESM today), then use .cjs only where tooling forces it.
