乐闻世界logo
搜索文章和话题

How to configure and use VS Code debugger?

2月18日 18:09

VS Code has built-in powerful debugging capabilities that support multiple programming languages and runtime environments. By configuring the launch.json file, you can customize debugging behavior.

Debug Configuration File

Debug configurations are stored in the .vscode/launch.json file:

json
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/app.js" } ] }

Common Configuration Properties

Basic Properties

  • type: Debugger type (node, python, java, etc.)
  • request: Request type (launch to start program, attach to attach to running process)
  • name: Configuration name
  • program: Path to the program to debug

Variable Substitution

  • ${workspaceFolder}: Workspace root directory
  • ${file}: Currently opened file
  • ${fileBasename}: Current file name (without path)
  • ${fileDirname}: Directory of the current file
  • ${env:Name}: Environment variable

Common Language Configuration Examples

Node.js

json
{ "type": "node", "request": "launch", "name": "Launch Node.js", "program": "${workspaceFolder}/index.js", "console": "integratedTerminal" }

Python

json
{ "type": "python", "request": "launch", "name": "Python: Current File", "program": "${file}", "console": "integratedTerminal" }

Chrome/Edge

json
{ "type": "chrome", "request": "launch", "name": "Launch Chrome", "url": "http://localhost:3000", "webRoot": "${workspaceFolder}" }

Debugging Features

Breakpoints

  • Line breakpoint: Click left of line number
  • Conditional breakpoint: Right-click > Add Conditional Breakpoint
  • Logpoint: Right-click > Add Logpoint

Debug Operations

  • F5: Start debugging
  • F10: Step over
  • F11: Step into
  • Shift+F11: Step out
  • Shift+F5: Stop debugging

Debug Console

During debugging, you can execute code and inspect variables in the debug console.

Advanced Features

Multi-configuration Debugging

json
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Server", "program": "${workspaceFolder}/server.js" }, { "type": "chrome", "request": "launch", "name": "Client", "url": "http://localhost:3000" } ], "compounds": [ { "name": "Server/Client", "configurations": ["Server", "Client"] } ] }

Task and Debug Integration

Automatically run build tasks before debugging:

json
{ "preLaunchTask": "npm: build", "type": "node", "request": "launch", "name": "Launch" }

Important Notes

  • Ensure the corresponding language debugging extension is installed
  • Source maps are important for TypeScript/compiled languages
  • Remote debugging requires correct port and network configuration
  • Debug configurations can be optimized for specific environments (development, testing, production)
标签:VSCode