ERR_MODULE_NOT_FOUND
ECMAScript module (ESM) import statement failed to resolve.
Usually happens because:
- ☑ Omitted File Extensions
- ☑ Missing module field targets inside
- ☑ Forgetting to define 'type'
🔍 Quick Checklist:
What is ERR_MODULE_NOT_FOUND?
The ERR_MODULE_NOT_FOUND error occurs when an ES Module (ESM) import statement fails to resolve. Unlike CommonJS require(), which resolves file extensions automatically, ES Modules inside Node.js mandate explicit file extensions (e.g. .js or .mjs) in relative paths.
Common Causes
- Omitted File Extensions: Attempting relative imports without adding .js or .mjs extensions (e.g. import './utils').
- Missing module field targets inside third-party packages.
- Forgetting to define 'type': 'module' inside package.json while executing ESM import syntax.
| Cause | Frequency |
|---|---|
| Omitted File Extensions | ⭐⭐⭐⭐⭐ |
| Missing module field targets inside | ⭐⭐⭐⭐ |
| Forgetting to define 'type' | ⭐⭐⭐ |
Common Mistakes
- Expecting Node.js ESM to resolve paths without extensions exactly like Webpack or TypeScript compilers do.
- Omitting 'type': 'module' inside package.json while executing ESM code.
How to Fix
Framework-Specific Examples
Setting up ES module routing correctly inside Express.
import express from 'express';
import { userRouter } from './routes/users.js'; // Note the mandatory .js extension
const app = express();
app.use('/users', userRouter);Server Configuration Examples
Vite/esbuild scripts automatically resolving extensions during production compilation.
# Compiles files to standard buildsBest Practices
- Configure ESLint rules to enforce explicit ESM import extensions.
- Use modern module bundlers (like Vite, esbuild, or TSUp) to compile outputs.
Frequently Asked Questions (FAQ)
Q: Why does ESM require file extensions in Node.js?
To match browser-native ESM specs. Browsers do not perform filesystem guesses (checking for .js, .json, index.js) like CommonJS did, so Node's ESM implementation mandates explicit extensions.
Q: What is the difference between MODULE_NOT_FOUND and ERR_MODULE_NOT_FOUND?
MODULE_NOT_FOUND is thrown by CommonJS (`require()`). ERR_MODULE_NOT_FOUND is thrown by ES Modules (`import`).
Q: How do I import JSON files in Node ESM?
You must use import assertions/attributes (e.g. `import data from './data.json' with { type: 'json' };` or `assert { type: 'json' }` depending on your Node.js version).
Q: Can I use directory imports (import './folder') in ESM?
No. ESM does not resolve `index.js` automatically. You must specify the full file path (e.g. `import './folder/index.js'`).