node express + typescript module not found error
Ive setup a simple node express app with typescript.
I want to add a errorMiddleware in the index.ts file.
When I start the server I am getting this error:
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (D:\ActiveProjects\rugBE\src\index.ts:1:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (C:\Users\UserName\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1371:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (C:\Users\UserName\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1374:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'D:\\ActiveProjects\\rugBE\\src\\index.ts' ]
my package.json:
{
"name": "rugbe",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"scripts": {
"dev": "nodemon src/index.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"ts-node": "^10.4.0"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^16.11.19",
"nodemon": "^2.0.15",
"typescript": "^4.5.4"
}
}
tsConfig:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": "src",
"paths": {
"Handlers/*": ["Handlers/*"]
},
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
index.ts:
import express from "express";
import errorMiddleWare from "Handlers/Error/handlerError"; // error here
// import notFoundMiddleWare from "Handlers/Error/notFound";
const app = express();
const port = 5000;
//@ts-ignore
app.get("/api", (_, res) => {
res.send("Hello World");
});
//notFound
// error
app.use(errorMiddleWare);
// app.all("*", notFoundMiddleWare);
app.listen(port);
The middleWare I am trying to import:
//@ts-ignore
const errorMiddleWare = (err, req, res, next) => {
// note params are the ones that tell if the errors should come here
const { statusCode, message } = err;
res.status(500).json({
status: "error",
statusCode: 500,
message,
});
next();
};
export default errorMiddleWare;
What have I missed?
Handlers
is an "bare" path. When you tell node to import a file starting not starting with a /
or ./
(or ../
) it will look for a module in your node_modules
directory with that name.
In order to add a file relative to your current directory (and other files) prefix it with ./
. The full algorithm is specified here if you want the full picture of how cjs (CommonJS modules) module loading works.
// Before, loads a Handlers package from node_modules
import errorMiddleWare from "Handlers/Error/handlerError"; // error here
// After, looks for a handlerError module in an
// Error folder inside the Handlers folder inside the current one
import errorMiddleWare from "./Handlers/Error/handlerError"; // error here