node.jstypescriptnodemontsconfigtsc

How to use TypeScript path on Node.js with tsc-watch?


I'm writing an application and decided to shorten paths using aliases. However, with all my settings I can't get Node.js to see the paths.

This is my tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist",
    "paths": {
      "@utils/*": ["src/utils/*"],
      "@controlers/*": ["src/controlers/*"],
      "@middlewares/*": ["src/middlewares/*"],
      "@routes/*": ["src/routes/*"],
      "@generated/*": ["/generated/*"]
    },
    "target": "es2024",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "resolveJsonModule": true,
    "sourceMap": false,
    "noImplicitAny": false,
    "removeComments": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}

This is my package.json:

"scripts": {
  "dev": "tsc-watch --onSuccess \"node -r tsconfig-paths/register ./dist/index.js\"",
  "test": "echo \"Error: no test specified\" && exit 1"
},
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module",
},
"devDependencies": {
    "nodemon": "^3.1.10",
    "ts-node": "^10.9.2",
    "tsc-watch": "^7.1.1",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.8.3"
},
  "_moduleAliases": {
    "@utils": "dist/utils",
    "@controlers": "dist/controlers",
    "@middlewares": "dist/middlewares",
    "@routes": "dist/routes",
    "@generated": "dist/generated"
}

How my inports in main TS file look:

import authRoutes from "@routes/auth_routes.js";

Also I tried nodemon with that setting, but this doesn't work either:

{
  "watch": ["src"],
  "ext": "ts, json",
  "exec": "node --loader ts-node/esm -r tsconfig-paths/register --experimental-specifier-resolution=node ./src/index.ts"
}

Ideally, I would like to run an application with real-time tracking without compilation, although if it is possible only with compilation then I am not against it. Of course, the simplest option is not to use all these paths and then everything will work, but why simplify everything.


Solution

  • Tsx node solve my problems with path, and work in live now! Link https://www.npmjs.com/package/tsx