kentor
kentor

Reputation: 18514

Debugging nest.js application with vscode

I am testing the nest.js framework but I am struggling to run it with VSCode so that I can properly debug my code. This is pretty much the same issue as described here Running nest.js from VS Code. However I made sure I am using the latest packages. I always get this error:

Error: Cannot find module 'cats/cats.module'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (c:\Users\user\Documents\random-api\dist\app.module.js:11:26)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)

npm run start works completely perfect, but I want to debug the application with the VSCode IDE.

My package.json dependencies:

  "dependencies": {
    "@nestjs/common": "^4.6.6",
    "@nestjs/core": "^4.6.6",
    "@nestjs/microservices": "^4.6.6",
    "@nestjs/testing": "^4.6.6",
    "@nestjs/websockets": "^4.6.6",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^5.5.7",
    "typescript": "^2.7.2"
  },
  "devDependencies": {
    "@types/express": "^4.11.1",
    "@types/jest": "^22.2.2",
    "@types/node": "^9.6.0",
    "@types/supertest": "^2.0.4",
    "jest": "^22.4.3",
    "nodemon": "^1.17.2",
    "prettier": "^1.11.1",
    "supertest": "^3.0.0",
    "ts-jest": "^22.4.2",
    "ts-node": "^5.0.1",
    "tsconfig-paths": "^3.1.3",
    "tslint": "5.9.1",
    "tslint-microsoft-contrib": "^5.0.3"
  },

My vscode's launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}\\dist\\main.js",
            "smartStep": true,
            "outFiles": [
                "${workspaceFolder}/dist/**/*.js"
            ]
        }
    ]
}

I tried the same launch.json with the typescript file as path, but that threw the same exception:

"program": "${workspaceFolder}\\src\\main.ts",

Upvotes: 97

Views: 149314

Answers (20)

ghiscoding
ghiscoding

Reputation: 13194

I tried the accepted answer and all the other variances and none worked for me, however what really works for me is to attach to the 9229 port. What I did is add/modify your launch.json with the following config

.vscode/launch.json

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach NestJS WS",
      "port": 9229,
      "restart": true,
      "stopOnEntry": false,
      "protocol": "inspector"
    }
  ]
}

and in package.json (Nest new CLI commands, requires 6.8.x and higher, see this blog)

{
  "name": "nest-app",
  "scripts": {
    "start:debug": "nest start --debug --watch"
  }
}

and finally it works!

EDIT

You could also try to use the new "Auto Attach: With Flag" and add --inspect to the end of the start:debug command as shown below, or use "Auto Attach: Always"

More info from VSCode website from either of these 2 links:

{
  "name": "nest-app",
  "scripts": {
    "start:debug": "nest start --debug --watch --inspect"
  }
}

Upvotes: 96

Daniel Schmitz
Daniel Schmitz

Reputation: 1340

Try this launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Nest Framework",
            "args": ["${workspaceFolder}/src/main.ts"],
            "runtimeArgs": ["--nolazy", "-r", "ts-node/register", "-r", "tsconfig-paths/register"],
            "sourceMaps": true,
            "cwd": "${workspaceRoot}",
            "protocol": "inspector"
        }
    ]
}

Upvotes: 117

kalinchernev
kalinchernev

Reputation: 31

In addition to auto-attach, it's also possible to start the app directly in JavaScript Debug Terminal

The naming of the command has changed compared to docs, Ctrl+Shift+P for "debug" and it will appear.

Basically, place a breakpoint, open the terminal, run the server as usual (even in monorepo workspace) and debug.

enter image description here

Upvotes: 1

user6365858
user6365858

Reputation:

This is what is working for me with Nest v10:

{
    "version": "0.2.0",
    "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Debug Nest Framework",
        "runtimeExecutable": "npx",
        "runtimeArgs": ["nest", "start", "--watch"],
        "sourceMaps": true,
        "outFiles": ["${workspaceFolder}/dist/**/*.js"],
        "cwd": "${workspaceFolder}",
        "skipFiles": ["<node_internals>/**"],
        "console": "integratedTerminal",
      }
    ]
}

The most important part is outFiles. It allows VS code to find your source maps that are generated in the dist folder.

You can also use npm script instead of npx:

{
    ...
    "runtimeExecutable": "npm",
    "runtimeArgs": ["run", "start:dev"],
}

If you are using a multi-root workspace in VS code, specify your folder name: "${workspaceFolder}" becomes "${workspaceFolder:folder-name}"

Upvotes: 4

Srikanth Reddy
Srikanth Reddy

Reputation: 56

One more approach that worked for me is with these launch.json settings.

  • Disable Auto attach in VS Code
  • Run NestJS application
  • Now press F5, VS Code then attaches to the debugger
  • You can now debug :)
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach",
      "port": 9229,
      "request": "attach",
      "skipFiles": ["<node_internals>/**"],
      "type": "node",
      "cwd": "${workspaceFolder}",
      "restart": true
    }
  ]
}

Upvotes: 0

kenberkeley
kenberkeley

Reputation: 9786

No need to mess up with .vscode/launch.json, just follow the official Auto Attach intro and ... Just Works!

For example, I wanna debug my project quiz:

  1. Toggle "Auto Attach" to "On"

Toggle Auto Attach

  1. Start a new terminal window (or restart)

  2. Run the app as usual, for this project is npm run server:dev

  3. When the app started successfully, attach to the process

Attach to Node process

  1. See the first one? Click on it! Done! Now you can click on breakpoints and inspect!

Pick the process

Upvotes: 123

Rafik Belkadi
Rafik Belkadi

Reputation: 394

This config should do the trick

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "npm dev",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "start:dev"],
      "console": "integratedTerminal"
    }
  ]
}

Upvotes: 5

hunter2009
hunter2009

Reputation: 153

No need to mess up with .vscode/launch.json. Just two steps:

  1. Alt + Shift + P open command bar.
  2. Toggle Debug: Toggle Auto Attach to On(smart,always....).

Then reopen terminal and start your debugge like in browser.

Upvotes: 4

elvin
elvin

Reputation: 981

If you don't want to spend too much time in getting the right launch.json file for your nestjs project and want to debug something in the startup process, you can still use the "attach debugger" approach using temporarily the method in your code waitForDebugger() available since v12.7.0. Then, you just need to run your start:debug script and attach the debugger using the VS Code command palette.

Upvotes: 1

Ofir
Ofir

Reputation: 326

Add this configuration to launch.json:

{
  "type": "node",
  "request": "launch",
  "name": "Launch NestJS",
  "program": "${workspaceFolder}/node_modules/@nestjs/cli/bin/nest.js",
  "args": [
    "start",
    "--tsc"
  ],
  "skipFiles": [
    "${workspaceFolder}/node_modules/**/*.js",
    "<node_internals>/**"
  ]
}

Upvotes: 1

Shyamal
Shyamal

Reputation: 51

Add this configuration to launch.json

 {
      "name": "npm run start:debug",
      "skipFiles": ["<node_internals>/**"],
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceRoot}",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "start:debug"],
      "port": 9229,
      "env": {
        "PORT": "5000" // env var used in app        
      }
    },

This will be with watch mode so whatever changes are made to .ts files it reflects immediately and makes sure you have the following script in package.json

    "start:debug": "nest start --debug --watch"

This will start the app in debug mode and attach debugger

Upvotes: 5

Srikanth Reddy
Srikanth Reddy

Reputation: 56

I'm using NestJs app in an Nx Workspace (Nx version 11.6.3), and it worked for me without using any launch.json settings.

In VS Code I have just enabled Auto Attach > Smart and I ran my NestJS app with the following command:
nx serve <nest-js-app-name> --inspect=inspect --port=9229
and VS Code automatically attaches the debugger.

My launch.json has a configuration to launch my frontend application while the above process automatically attaches the debugger when you start the NestJS application. This way I have both frontend and backend launched at the same time for debugging.

Upvotes: 1

Илья Хоришко
Илья Хоришко

Reputation: 1195

If you get an error like this

could not read source map for node_modules / typescript / lib / typescript.js

setting the "type" to "pwa-node" instead of "node"

If you get an error like this

Cannot find module src/interceptors/auth.interceptor

setting the "runtimeArgs" to

      [
        "--nolazy",
        "-r",
        "ts-node/register",
        "-r",
        "tsconfig-paths/register"
      ]

instead of

[
   "--nolazy", "-r", "ts-node/register"
]

Result:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-node",
      "request": "launch",
      "name": "Debug Nest Framework",
      "args": ["${workspaceFolder}/src/main.ts"],
      "runtimeArgs": [
        "--nolazy",
        "-r",
        "ts-node/register",
        "-r",
        "tsconfig-paths/register"
      ],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}"
      //   "protocol": "inspector"
    }
  ],
  "resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"]
}

BUT I use this config

{
  "version": "0.2.0",
  "configurations": [
      {
          "type": "node",
          "request": "launch",
          "name": "Debug Nest Framework",
          "args": [
              "${workspaceFolder}/src/main.ts"
          ],
          "runtimeArgs": [
              "--nolazy",
              "-r",
              "ts-node/register",
              "-r",
              "tsconfig-paths/register"
          ],
          "sourceMaps": true,
          "envFile": "${workspaceFolder}/.env",
          "cwd": "${workspaceRoot}",
          "console": "integratedTerminal",
          "protocol": "inspector"
      },
      {
        "name": "Debug Jest Tests",
        "type": "node",
        "request": "launch",
        "runtimeArgs": ["--inspect-brk", "${workspaceRoot}/node_modules/.bin/jest", "--runInBand", "--coverage", "false"],
        "console": "integratedTerminal"
    }
  ]
}

Thanks this site: Click me

Upvotes: 4

Sasha Ladnov
Sasha Ladnov

Reputation: 491

If you want to have log output in terminal + all debug capabilities, you can start + attach using npm, here is config for launch.json:

{
  "type": "node",
  "request": "launch",
  "name": "Nest Debug",
  "runtimeExecutable": "npm",
  "runtimeArgs": [
    "run",
    "start:debug",
    "--",
    "--inspect-brk"
  ],
  "console": "integratedTerminal",
  "restart": true,
  "protocol": "auto",
  "port": 9229,
  "autoAttachChildProcesses": true
},

Will show full log output in console + debugging

Upvotes: 49

Jasim Khan Afridi
Jasim Khan Afridi

Reputation: 776

For people using Nrwl:

Launch.json (courtesy of @ghiscoding )

{
      "type": "node",
      "request": "attach",
      "name": "Attach NestJS WS",
      "port": 9229,
      "restart": true,
      "stopOnEntry": false,
      "protocol": "inspector"
    }

Terminal

ng serve nestjs_project --port 9229

Upvotes: 5

David
David

Reputation: 1458

I just have to "promote" this comment by @JWess to a real answer (and update it with the current location of the relevant setting) so it may be found more easily (this worked for me out of the box for a newly generated nest project, without changing any other configuration or file):

If you go to Settings > Extensions > Node debug and look for the setting Debug › Node: Auto Attach and turn it on, VSCode will auto-attach when you run npm run start:debug (i.e. nest start --debug --watch) in the integrated terminal.

Upvotes: 2

Priyabrata Pati
Priyabrata Pati

Reputation: 85

What I did was auto attach the vs code debugging process with one of my scripts in package.json. And on top of it I used nodemon, which would automatically restart up along with the debugger, if you have made any changes in development.

The process requires you to install nodemon globally and add a nodemon-debug.json file in the root of the folder, which looks like this.

nodemon-debug.json

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

Then in the package.json, add a script that looks like this

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

Then in the VS Code, hit F1 > search for Debug: Toggle Auto Attach. Hit on it to enable it.

Then start up the debugging process by running the following command -

npm run debug

The debugger automatically turns on.

The advantage of this process is nodemon, which automatically starts along with the debugger every time you make some changes in the code and need it up.

For a more detailed explanation, go through this link. Worked for me.

Upvotes: 2

Nelson Bwogora
Nelson Bwogora

Reputation: 2369

in launch.json have

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/linkid=830387
  "version": "0.2.0",
   "configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Debug Nest Framework",
        "args": ["${workspaceFolder}/src/main.ts"],
        "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
        "sourceMaps": true,
        "cwd": "${workspaceRoot}",
        "protocol": "inspector"
    }
   ]
  }

Upvotes: 3

chavy
chavy

Reputation: 1068

This settings works for me

{
  "name": "Launch app",
  "type": "node",
  "request": "launch",
  "args": [
    "src/main.ts"
  ],
  "runtimeArgs": [
    "-r",
    "ts-node/register",
    "-r",
    "tsconfig-paths/register"
  ],
  "cwd": "${workspaceRoot}",
  "protocol": "inspector",
  "internalConsoleOptions": "openOnSessionStart",
  "env": {
    "NODE_ENV": "local",
    "NODE_PORT": "9000"
  },
  "sourceMaps": true,
  "console": "internalConsole",
  "outputCapture": "std"
}

Get it from here

Upvotes: 6

Sandeep K Nair
Sandeep K Nair

Reputation: 2932

Here is a config that works. Hope this helps someone :)

Make sure you add tsconfig-paths/register line under runtimeArgs else you will get an error saying some of your user defined modules were not found.

Also replace <YOUR_APP_ROOT_FOLDER> name with your application folder name if you have one under your root project folder, else remove it from the path in the script.

Note: Make sure to stop running your app before executing this debug config on vscode, because this debug script will launch a new instance of your app on the same port.

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Nest Framework",
            "args": [
                "${workspaceFolder}/<YOUR_APP_ROOT_FOLDER>/src/main.ts"
            ],
            "runtimeArgs": [
                "--nolazy",
                "-r",
                "ts-node/register",
                "-r",
                "tsconfig-paths/register"
            ],
            "sourceMaps": true,
            "cwd": "${workspaceRoot}/<YOUR_APP_ROOT_FOLDER>",
            "protocol": "inspector"
        }
    ]
}

Upvotes: 7

Related Questions