How to debug using npm run scripts from VSCode? Ask Question

How to debug using npm run scripts from VSCode? Ask Question

I was previously using gulp and running gulp to start my application and listeners from the Visual Studio Code debugger but have recently needed to switch to running scripts through npm instead. Unfortunately in VSCode I've not been able to run npm scripts through the debugger so I've had to resort to running node to start my server directly which gets rid of my listener tasks which reloaded code automatically.

This seems like something that should be simple but so far I haven't had much luck. Below is a snippet from my launch.json file that I attempted to use but npm could not be located.

{
    ...
        "program": "npm",
        "args": [
            "run",
            "debug"
        ],
    ...
}

This gives me the following error.

Error request 'launch': program 'c:\myproject\npm' does not exist

Related resources:

ベストアンサー1

It appears that VS Code will support npm scripts and other launch scenarios since the release from October 2016.

Below is an example as it was proposed on GitHub but has been adjusted to use --inspect-brk instead of the originally prposed --debug-brk option.

packages.json

  "scripts": {
    "debug": "node --nolazy --inspect-brk=5858 myProgram.js"
  },

vscode launch config

{
    "name": "Launch via NPM",
    "type": "node",
    "request": "launch",
    "cwd": "${workspaceRoot}",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
        "run-script", "debug"
    ],
    "port": 5858
}

More recent updates for Visual Studio Code as of Summer of 2022 show that there are various ways to set up debugging support with Node.js. These methods include auto attaching to either processes started from the VSCode Integrated Terminal or the JavaScript debug terminal, or by using the traditional launch config which is now extensively documented.

おすすめ記事