npm Cannot find module — how to fix
Quick Answer
# Install the missing module
npm install xyz
# If it's a dev dependency
npm install --save-dev xyz
# Rebuild node_modules from scratch
rm -rf node_modules package-lock.json
npm install
When this happens
Error: Cannot find module 'express'
Require stack:
- /home/user/project/src/index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
Node.js cannot locate the module because it is not installed, the package name is misspelled, or node_modules is missing.
Other causes & fixes
Check if it is installed
# List installed packages
npm ls express
# Or check node_modules
ls node_modules/express
Relative path import errors
For local file imports, check the path is correct relative to the importing file.
// WRONG — missing ./ prefix
const utils = require('utils'); // looks in node_modules
// CORRECT — explicit relative path
const utils = require('./utils');
const utils = require('../lib/utils');
TypeScript — missing @types package
# Install type definitions
npm install --save-dev @types/express
# Or check if types are bundled
npm info express types
ESM vs CJS mismatch
# package.json "type": "module" uses ESM — use import instead of require
import express from 'express';
# Or rename file to .cjs to use CommonJS
// index.cjs
const express = require('express');
Related