答案:通过配置VS Code的compound launch实现全栈调试,先确保前后端可独立调试,再在launch.json中定义Debug Backend和Debug Frontend两个配置,并创建名为Debug Full Stack的复合配置,结合preLaunchTask自动启动服务,最终一键同时调试前后端代码。
要在 VS Code 中同时调试前端和后端,可以通过配置 复合启动配置(compound launch configuration) 实现。这种方式允许你一键启动多个调试会话,比如 Node.js 后端和 React/Vue 前端。
在设置多目标调试前,先确认前端和后端都能单独运行和调试:
launch.json 启动调试。打开 VS Code 的 .vscode/launch.json 文件,定义两个独立的启动配置,并通过 compound 将它们组合:
rkspaceFolder}/dist/**/*.js"]
},
{
"name": "Debug Frontend",
"type": "pwa-chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/client/src"
}
],
"compounds": [
{
"name": "Debug Full Stack",
"configurations": ["Debug Backend", "Debug Frontend"],
"stopAll": true
}
]
}
说明:
configurations 定义了两个独立的调试任务。compound 中的 configurations 数组列出要同时启动的调试配置名称。stopAll: true 表示点击停止时,所有相关进程都会被终止。上述配置只负责“调试”已运行的服务。若希望 VS Code 自动启动前后端进程,需结合 preLaunchTask 使用:
tasks.json 任务(如 npm start:client 和 npm start:server)。launch.json 的每个配置中添加 preLaunchTask 来自动运行对应命令。例如,在 “Debug Backend” 配置中加入:
"preLaunchTask": "start server"然后在 .vscode/tasks.json 中定义该任务:
注意:前端服务可能需要等待构建完成后再打开浏览器,可使用 resolveSourceMapLocations 或延迟加载策略避免断点失效。
按 F5,选择 “Debug Full Stack” 启动项,VS Code 会:
基本上就这些。只要项目结构清晰、启动脚本明确,VS Code 的 compound 调试功能就能很好地支持全栈开发调试。