1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Isn't there a way for me to configure this so that I can have the path like this and tell the compiler not to look in node-modules? Thats why I added paths in the tsconfig and the exclude of node modules in tsconfig aswell. You are correct that "./" works but I am trying to have it direct.
@CodingLittle yes, either with npmjs.com/package/tsconfig-paths (using the same sort of config you are using for cjs). That package exists for this use case. I don't like it (because module resolution is hard enough as it is to figure out) but it's a possibility and YMMV :)
I might be asking alot from you in this answer but Im struggling to get it to work. I installed the linked package but getting the same error.
@CodingLittle feel free to open concrete isolated questions and ping me, I can't help with "It doesn't work" and the original answer demonstrates you know how to ask here. (After installing that package make sure you follow its instructions and specify Handlers in your tsconfig.json's "paths" section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.