ES modules vs CommonJS in Node.js: `require is not defined` error
poze a month ago432 gadeen
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?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
"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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.