What is the proper way to debug an npm script usin

2020-02-10 12:48发布

问题:

I've got an npm script that I'm trying to debug. I use vscode so I thought I'd create a debug configuration and step through it with the debugger.

My npm script look is:

"scripts": {
    ...
    "dev": "node tasks/runner.js",
}

So I created the following debug config:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "runtimeExecutable": "npm",
            "cwd": "${workspaceRoot}",
            "runtimeArgs": [
                "run", "dev"
            ],
            "port": 5858,
            "stopOnEntry": true
        }
    ]
}

And when I fire it the script runs, but vscode is never able to connect and I get the error:

Cannot connect to runtime via 'legacy' protocol; consider using 'inspector' protocol (timeout after 10000 ms).

I tried adding an inspector protocol:

       {
            "type": "node",
            "request": "attach",
            "name": "Attach (Inspector Protocol)",
            "port": 9229,
            "protocol": "inspector"
       }

And running the npm script via:

npm run dev --inspect

And this time I get the error:

Ensure Node was launched with --inspect. Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9229).

I'm not sure what part I'm missing.

Edit per duplicate tag

I see the other question re: debugging an npm script via vscode, but the details in the other question and answers aren't as detailed and specific. If someone is searching for the specific vscode error messages I ran into or the config type I had they wouldn't necessarily get the level answer detail that this question's chosen answer gives.

回答1:

You shouldn't try to debug the npm script because what you really want is to attach your debugger to the script that is launched with npm run command (NPM here is used only as a task runner).

{
  "version": "0.2.0",
  "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "program": "${workspaceRoot}/tasks/runner.js"
      }
  ]
}

If you really want to run it using npm script, then you can use the following configuration:

{
  "type": "node",
  "request": "launch",
  "name": "Launch via NPM",
  "runtimeExecutable": "npm",
  "windows": {
    "runtimeExecutable": "npm.cmd"
  },
  "runtimeArgs": [
    "run-script",
    "dev"
  ],
  "port": 5858
}

but you also have to change your script command (specify a debug port)

  "scripts": {
    "dev": "node --nolazy --debug-brk=5858 tasks/runner.js"
  },

You can explore various debug configurations simply by clicking the gear icon and selecting one.

More about Node.js debugging can be found in the VS Code documentation.