首先理解 Debug Adapter Protocol(DAP),它是 VSCode 与调试器通信的 JSON-RPC 协议,包含请求、响应和事件三类消息;接着使用 yo code 生成扩展骨架,在 package.json 中注册调试类型 my-debugger,并声明 launch 配置;然后实现 Debug Adapter,通过继承 vscode-debugadapter 提供的 DebugSession 类,重写 launchRequest 和 setBreakPointsRequest 等方法处理调试逻辑;最后在 extension.ts 中注册 DebugAdapterDescriptorFactory,使 VSCode 能启动适配器进程;完成上述步骤后,F5 即可启用调试功能。

开发自定义调试器适配器(Debug Adapter)让 VSCode 能够支持任意语言或运行时的调试功能。整个流程涉及协议理解、适配器实现、扩展注册和调试通信。以下是完整开发流程,帮助你从零构建一个可用的调试扩展。
VSCode 通过 Debug Adapter Protocol (DAP) 与调试器通信。DAP 是基于 JSON-RPC 的通用协议,定义了编辑器与调试后端之间的消息格式。核心概念包括:
你需要实现一个程序,能监听来自 VSCode 的 DAP 请求,并按协议返回正确响应。
使用 vscode-generator-code 快速生成扩展骨架:
yo code选择“New Extension (TypeScript)”或“New Debug Adapter extension”。生成后,重点关注以下文件:
在 package.json 中添加调试贡献点:
"contributes": { "debuggers": [ { "type": "my-debugger", "label": "My Debugger", "languages": ["mylang"], "configurationAttributes": { "launch": { "required": ["program"], "properties": { "program": { "type": "string", "description": "The program to debug" } } } }, "adapterExecutableCommand": "my-debug-adapter" } ] }这告诉 VSCode 支持名为 my-debugger 的调试类型。
Debug Adapter 可以是独立进程或内联脚本。常见方式是用 Node.js 编写并作为子进程启动。
关键步骤:
示例代码片段(TypeScript):
import { DebugSession, LoggingDebugSession } from 'vscode-debugadapter'; import { DebugProtocol } from 'vscode-debugprotocol';class MyDebugAdapter extends LoggingDebugSession { protected launchRequest(response: DebugProtocol.LaunchResponse, args: any) { // 启动目标程序,建立通信 this.sendResponse(response); // 模拟程序启动成功 this.fireEvent({ type: 'event', event: 'initialized' }); }
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: any) { // 处理断点设置 const breakpoints = args.breakpoints.map(() => ({ verified: true, line: args.line })); response.body = { breakpoints }; this.sendResponse(response); } }
// 启动适配器 DebugSession.run(MyDebugAdapter);
编译后生成 debugAdapter.js,供扩展调用。
在 extension.ts 中注册适配器启动逻辑:
import * as vscode from 'vscode'; import * as net from 'net'; import * as path from 'path';export function activate(context: vscode.ExtensionContext) { const factory = new DebugAdapterExecutableFactory(context); context.subscriptions.push( vscode.debug.registerDebugAdapterDescriptorFactory('my-debugger', factory) ); }
class DebugAdapterExecutableFactory implements vscode.DebugAdapterDescriptorFactory { createDebugAdapterDescriptor(session: vscode.DebugSession): vscode.ProviderResult<vscode.DebugAdapterDescriptor> { return new vscode.DebugAdapterExecutable( 'node', [path.join(__dirname, '../out/debugAdapter.js')], {} ); } }
这样,当用户启动调试会话时,VSCode 会自动运行你的适配器脚本。
基本上就这些。完成之后,按下 F5 启动调试,VSCode 将通过 DAP 与你的适配器通信,实现断点、变量查看、单步执行等功能。建议结合 vscode-debugadapter 提供的日志功能排查问题,逐步扩展对复杂调试操作的支持。
以上就是VSCode调试扩展:开发自定义调试器适配器的完整流程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号