ERR_REQUIRE_ESM
The ERR_REQUIRE_ESM error means you used require() on an ES module. Fix it by using import, renaming to .cjs, or adding "type": "commonjs" to package.json.
What It Means
Since Node.js 12, the module system supports two formats: CommonJS (.js/.cjs, using require() and module.exports) and ES modules (.js/.mjs, using import/export). A file is treated as ESM if its extension is .mjs or if the nearest package.json contains "type": "module". Calling require() on an ESM file throws ERR_REQUIRE_ESM because require() is synchronous and ESM modules are asynchronously loaded.
Why It Happens
- Your
package.jsonhas"type": "module"and you’re trying torequire()another ESM module. - You’re using
require()on a package that ships only as ESM (e.g.,chalkv5+,node-fetchv3+). - You renamed a file to
.mjsbut still userequire()in a CommonJS file trying to load it. - You’re mixing module systems in a project that doesn’t have a consistent
"type"field.
How to Fix It
1. Use import() instead of require() (dynamic import)
// Instead of:
const chalk = require('chalk');
// Use dynamic import (works in both CJS and ESM):
const chalk = await import('chalk');Note: import() returns a Promise, so you need async context.
2. Switch your project to ES modules (use import everywhere)
Set "type": "module" in package.json:
{
"type": "module"
}Then replace require() with import:
import chalk from 'chalk';
import fs from 'fs/promises';3. Rename the file to .cjs (keep using require)
If you can’t or don’t want to convert the whole project to ESM, rename the specific file to .cjs:
mv src/config.js src/config.cjsThen require() works normally on .cjs files regardless of the "type" field.
4. Set "type": "commonjs" explicitly in package.json
{
"type": "commonjs"
}This makes .js files default to CommonJS. If the package you’re trying to load is ESM-only (like chalk 5+), you’ll still need to use import() instead of require().
5. Use a bundler (Webpack / Rollup / esbuild)
Bundlers handle module system interop automatically:
npm install --save-dev esbuild
npx esbuild src/index.js --bundle --outfile=dist/bundle.jsBuilt by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro