ES modules vs CommonJS in Node.js: `require is not defined` error

asked a month ago436 viewsen

1

After adding "type": "module" to package.json I get ReferenceError: require is not defined in ES module scope. Without it, import statements fail. What's the right setup in 2026?

Environment:Node.js 22Node.js 22

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked a month ago

1 Answer

3
✓
✓ Accepted answer

"type": "module" tells Node to treat .js files as ES modules, where require, module.exports and __dirname don't exist.

For new projects, go all-in on ESM:

import fs from 'node:fs/promises';
import path from 'node:path';

const dir = import.meta.dirname; // Node 20.11+ replacement for __dirname

If you must load a CommonJS-only package, a default import usually works (import pkg from 'old-lib'). As a last resort:

import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

Recent Node versions (22.12+) can also require() ES modules synchronously, which removes most of the old interop pain.

Sign in to tell others whether this worked.

answered a month ago

Sign in and verify your email to post an answer.