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
13
Related Errors
JavaScript
ReferenceError: X is not defined
The code references a variable or function that hasn't been declared.
Frontend
ResizeObserver Loop Limit Exceeded
A ResizeObserver callback triggered layout changes that caused another resize, creating an infinite loop.
Frontend
Webpack Module Not Found
Webpack cannot resolve a module or file imported in the code.
Node.js
Unhandled Promise Rejection
A Promise was rejected but no error handler was attached to catch the rejection.