Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging Nest App using path mapping by TS

I am trying to debug a typescript-node app (by nestjs) but as I included the path mapping by Typescript ->

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

it doesn't work anymore, it throws this error:

enter image description here

Debug config file looks like this:

enter image description here

And TSCONFIG file looks like this:

enter image description here

Just to mention that the app works fine, the tests are passing fine and everything is working as expected, except when I press play to debug de app.

A work-around is to replace those paths by the relative normal path to be imported, but that means getting rid of the path mapping feature brought by TS and that's my last shot.

like image 469
Alejandro Lora Avatar asked Jul 28 '18 20:07

Alejandro Lora


1 Answers

I got the solution for this. I am going to detail the steps in case it helps someone else.

When adding path mapping to your project, you get the chance of using shorter and absolute paths to modules, which it has some pros/const but generally I think it's great when working with modules.

Problem might come when testing, debugging or running the app differently than when you work in dev mode.

So using jest, you need to add:

"jest": {
    "moduleFileExtensions": [ ... ],
    "moduleNameMapper": {
      "@db/(.*)": "<rootDir>/core/database/$1",
      "@exceptions/(.*)": "<rootDir>/core/exceptions/$1",
      "@permissions/(.*)": "<rootDir>/permissions/$1",
      "@roles/(.*)": "<rootDir>/roles/$1",
      "@users/(.*)": "<rootDir>/users/$1",
      "@videos/(.*)": "<rootDir>/videos/$1"
    },
    "rootDir": "src",
    ...

Then for debugging, I needed to do the following steps:

1) Update launch.json in vscode:

        {
            "type": "node",
            "request": "launch",
            "name": "Nest Debug",
            "runtimeExecutable": "npm",
            "runtimeArgs": [
                "run-script",
                "debug"
            ],
            "port": 9229
        },

2) Update package.json scripts to add:

"debug": "nodemon --config nodemon-debug.json",

3) Install tsconfig-paths - (npm install --save-dev tsconfig-paths)

https://github.com/dividab/tsconfig-paths

4) Create/Update nodemon-debug.json file:

{
  "watch": [
    "src"
  ],
  "ext": "ts",
  "ignore": [
    "src/**/*.spec.ts"
  ],
  "exec": "node --inspect-brk -r ts-node/register -r tsconfig-paths/register src/main.ts"
}

Notice this line

node --inspect-brk -r ts-node/register -r tsconfig-paths/register src/main.ts

Difference with nodemon.json is:

  • Nodemon.json: "exec": "ts-node -r tsconfig-paths/register src/main.ts"
  • Nodemon-debug.json: "exec": "ts-node -r tsconfig-paths/register -r tsconfig-paths/register src/main.ts"
like image 58
Alejandro Lora Avatar answered Sep 29 '22 16:09

Alejandro Lora