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

VS Code 调试器如何配置和使用?

2月18日 18:09

VS Code 内置了强大的调试功能,支持多种编程语言和运行时环境。通过配置 launch.json 文件,可以自定义调试行为。

调试配置文件

调试配置存储在 .vscode/launch.json 文件中:

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

常用配置属性

基本属性

  • type: 调试器类型(node, python, java 等)
  • request: 请求类型(launch 启动程序,attach 附加到运行中的进程)
  • name: 配置名称
  • program: 要调试的程序路径

变量替换

  • ${workspaceFolder}: 工作区根目录
  • ${file}: 当前打开的文件
  • ${fileBasename}: 当前文件名(不含路径)
  • ${fileDirname}: 当前文件所在目录
  • ${env:Name}: 环境变量

常见语言配置示例

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}" }

调试功能

断点

  • 行断点:点击行号左侧
  • 条件断点:右键 > Add Conditional Breakpoint
  • 日志点:右键 > Add Logpoint

调试操作

  • F5: 开始调试
  • F10: 单步跳过
  • F11: 单步进入
  • Shift+F11: 单步跳出
  • Shift+F5: 停止调试

调试控制台

在调试过程中,可以在调试控制台中执行代码和检查变量。

高级功能

多配置调试

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"] } ] }

任务与调试集成

在调试前自动运行构建任务:

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

注意事项

  • 确保安装了对应语言的调试扩展
  • 源码映射(Source Maps)对于 TypeScript/编译语言很重要
  • 远程调试需要正确配置端口和网络
  • 调试配置可以针对特定环境进行优化(开发、测试、生产)
标签:VSCode