启动Express服务器时Node.js持续抛出模块找不到错误的求助
Let's break down what's causing these errors and how to fix them quickly:
The Core Issue: Module Resolution Rules
Node.js and TypeScript handle module imports differently based on the path format:
- Relative paths (starting with
./or../) tell Node to look for your local files/folders starting from the current file's directory. - Bare module names (like
routesordatabase) make Node search for third-party packages in yournode_modulesfolder, not your project's source code. That's why your first error popped up—Node was trying to find a npm package namedroutesinstead of your local routes folder.
Quick Fix: Use Correct Relative Paths
Update all your local module imports to use relative paths that match your project structure:
In
src/index.ts:
Changeimport routes from "routes";to:import routes from "./routes";(This works if your
routesfolder is in the samesrcdirectory asindex.ts.)In
src/models/User.ts:
Your error shows it's trying to importdatabase—adjust this path based on where your database files live. For example:- If
databaseis a folder insrc/(same level asmodels), use:import database from "../database"; - If
databaseis a file insidesrc/models/, use:import database from "./database";
- If
Optional: Set Up Non-Relative Imports (For Large Projects)
If you want to avoid messy relative paths like ../../database, you can configure TypeScript to resolve bare module names to your local source files:
Update
tsconfig.json:
Add these settings to thecompilerOptionssection:{ "compilerOptions": { "baseUrl": "./src", // Set your src folder as the root for module resolution "paths": { "*": ["*"] // Map all bare module names to files in src }, // Keep your existing compiler options here } }Install
tsconfig-paths:
This package lets Node.js recognize TypeScript's path configuration:npm install tsconfig-paths --save-devAdjust your start command:
Modify your package.json scripts to use the path register:{ "scripts": { "start": "ts-node -r tsconfig-paths/register src/index.ts" } }Now you can use
import routes from "routes"andimport database from "database"without relative paths.
Final Checks
- Double-check that the files/folders you're importing actually exist (e.g., make sure
routes/index.tsexists—TypeScript automatically imports theindex.tsfile from a folder). - Ensure filename casing matches exactly. Windows ignores case, but Node.js might throw errors if you import
Routes.tsinstead ofroutes.ts.
内容的提问来源于stack exchange,提问作者Ahmad ELZohairy

