What is the correct way to debug an npm script using vscode?

I have an npm script that I am trying to debug. I am using vscode, so I decided to create a debug configuration and execute it using a debugger.

My npm script number is as follows:

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

So, I created the following debug configuration:

 { "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 run it, the script runs, but vscode can never connect, and I get the error message:

Unable to connect to runtime via the 'legacy' protocol; consider using the inspector protocol (latency after 10,000 ms).

I tried to add an inspector protocol:

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

And run npm script with:

 npm run dev --inspect 

And this time I get an error message:

Make sure Node is running with --inspect. Unable to connect to the execution process, timeout after 10000 ms - (reason: cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9229).

I'm not sure which part I am missing.

Edit for each duplicate tag

I see another question: debugging an npm script via vscode, but the details in other questions and answers are not as detailed and specific. If someone is looking for specific vscode error messages that I stumbled upon, or the type of configuration that I had, they will not necessarily get a detailed answer to the level that this question of your choice gives.

+15
source share
1 answer

You should not try to debug an npm script , because you really want to connect your debugger to a script that is launched using the npm run command (NPM is used only as a task runner here).

 { "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 an npm script, 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 must also change your script command (specify the debug port)

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

You can explore the various debugging configurations by simply clicking the gear icon and selecting one of them.

enter image description here

More information on Node.js debugging can be found in the VS Code Documentation .

+20
source

Source: https://habr.com/ru/post/1266316/


All Articles