How to debug a nodemon project in VSCode

后端 未结 6 1737
醉酒成梦
醉酒成梦 2021-02-04 01:19

I have a NodeJs project and I run it using nodemon,
I wish to run it in debug mode for development tasks, but I am unable to do so.

I found that I\'ll need to ad

6条回答
  •  迷失自我
    2021-02-04 01:58

    You can launch and attach nodemon with F5, however it will require a little more setup.

    We will have to first pre-launch nodemon via VS Code task and then attach.

    I'm using remote debugger to attach since it does not require additional clicks to select the process to attach, and VS Code process picker is currently broken in WSL2, which is my main development environment.

    tasks.json (from this answer):

    {
      "version": "2.0.0",
      "tasks": [
        {
          "label": "npm dev",
          "type": "npm",
          "script": "dev",
          "isBackground": true,
    
          // This task is run before some debug tasks.
          // Problem is, it's a watch script, and since it never exits, VSCode
          // complains. All this is needed so VSCode just lets it run.
          "problemMatcher": [
            {
              "pattern": [
                {
                  "regexp": ".",
                  "file": 1,
                  "location": 2,
                  "message": 3
                }
              ],
              "background": {
                "activeOnStart": true,
                "beginsPattern": ".",
                "endsPattern": "."
              }
            }
          ]
        }
      ]
    }
    

    launch.json:

    {
      "type": "node",
      "request": "attach",
      "name": "Launch & Attach",
      "restart": true,
      "localRoot": "${workspaceRoot}",
      "remoteRoot": "${workspaceRoot}",
      "preLaunchTask": "npm dev"
    }
    

    And in npm dev script (for node >= 6.9):

    nodemon --watch src -e js --exec node --inspect .
    

    Note - this approach won't work if your process takes more than 10 seconds to start. In that case you will have to figure out how to signal VS Code when the pre-launch task has finished. This probably can be achieved by playing with beginsPattern / endPattern regex, though I haven't tried it.

提交回复
热议问题