ERR_REQUIRE_ESM
Node.js cannot require() an ES module; use import() instead.
Explanation
ERR_REQUIRE_ESM occurs when you try to use CommonJS require() to load a module that is an ES module. Starting with Node.js 14, packages can be ES modules (using import/export syntax) and cannot be loaded with require(). This error has become increasingly common as more npm packages switch to ESM-only. The error message suggests using dynamic import() instead, which returns a Promise.
Common Causes
- Package is ESM-only but using require()
- Missing "type": "module" in package.json
- Node.js version too old for ESM
- Package doesn't provide CommonJS build
- Build output not compatible
Solution
Convert your code to use ES module syntax (import/export) by adding "type": "module" to package.json. Use dynamic import() for async loading: const module = await import('package'). Use createRequire() from the module module to create a require function that works with ESM. Check if the package provides a CommonJS build. Consider using a build tool like esbuild or tsup that can convert ESM to CommonJS.
Code Example
// This causes ERR_REQUIRE_ESM
const somePackage = require('some-esm-package'); // Error!
// Fix 1: Use dynamic import()
const somePackage = await import('some-esm-package');
// Fix 2: Add "type": "module" to package.json and use import
import somePackage from 'some-esm-package';
// Fix 3: Use createRequire
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const somePackage = require('some-esm-package');
// Fix 4: Check if package has CommonJS build
const somePackage = require('some-esm-package/dist/cjs/index.js');
// For TypeScript projects
// tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler"
}
}
Error Information
Language
javascript
Framework
nodejs
Difficulty
Intermediate
Views
371
Related Errors
ERR_MODULE_NOT_FOUND
Node.js
ERR_MODULE_NOT_FOUND
Node.js cannot find the specified ES module file.
General
Circular Dependency Detected
Module A depends on B which depends on A, creating an unresolvable import cycle.
EADDRINUSE
DevOps
Port Already in Use
The application cannot start because the required port is already occupied by another process.
Database
TypeORM/SQLAlchemy EntityNotFoundError
The ORM cannot find the requested entity or model in the database.