如何在VS Code扩展中为当前文档添加动态生成的JSON Schema
动态为当前JSON文档应用生成的JSON Schema的正确实现
核心逻辑
VSCode的JSON语言服务不支持直接调用languageService.setSchema来绑定动态Schema,正确方式是实现自定义JSONSchemaProvider接口,通过注册提供者的方式,针对指定文档URI返回动态生成的Schema。
具体实现步骤
1. 实现自定义Schema提供者
创建类实现vscode.JSONSchemaProvider,仅对目标文档返回动态Schema:
class DynamicSchemaProvider implements vscode.JSONSchemaProvider { private targetUri: string; private dynamicSchema: vscode.JSONSchema; constructor(uri: string, schema: vscode.JSONSchema) { this.targetUri = uri; this.dynamicSchema = schema; } async provideSchema(uri: vscode.Uri): Promise<vscode.JSONSchema | undefined> { // 仅匹配目标文档URI时返回动态Schema if (uri.toString() === this.targetUri) { return this.dynamicSchema; } return undefined; } }
2. 整合已有代码完成流程
结合你获取文档URI、生成Schema的逻辑,修改为以下可运行代码:
// 获取当前激活的JSON文档 const editor = vscode.window.activeTextEditor; if (!editor || editor.document.languageId !== 'json') { vscode.window.showErrorMessage('请先打开一个JSON文档'); return; } const document = editor.document; const uri = document.uri; // 动态生成目标Schema(沿用你原有的结构) const dynamicSchema: vscode.JSONSchema = { type: 'object', properties: { packages: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, tasks: { type: 'array', items: { type: 'object', properties: { Data: { type: 'array', items: { type: 'object', properties: { attributeName: { type: 'string', enum: ['1', '2'] }, flow: { type: 'string' }, visibility: { type: 'string' } } } } } } } } } } } }; // 创建并注册提供者 const schemaProvider = new DynamicSchemaProvider(uri.toString(), dynamicSchema); const disposable = vscode.languages.registerJSONSchemaProvider('json', schemaProvider); // 将提供者加入扩展订阅,确保停用后自动销毁 context.subscriptions.push(disposable);
3. 关键注意点
- 禁止直接操作
languageService,必须通过官方扩展API的提供者机制实现 - 提供者要严格匹配目标文档URI,避免影响其他JSON文件的Schema关联
- 注册的提供者必须添加到
context.subscriptions,防止内存泄漏
内容的提问来源于stack exchange,提问作者agebrock
相关产品推荐
相关产品推荐

