Monaco Editor 实现基于 JSON Schema 的智能提示

最近使用monaco-editor来实现JSON数据编辑器,为了提升用户体验,需要实现JSON Schema的智能提示。研究后发现了实现方法,因此这里Mark下。

实现

使用monaco-editor的语言服务,实现JSON Schema的智能提示。

设置JSON Schema

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
schemas: [
{
uri: "http://myschema/abi-schema.json",
fileMatch: [model.uri.toString()],
schema: {
type: "array",
items: {
type: "object",
required: ["type"],
properties: {
name: {
type: "string",
description: "函数或事件名称"
},
type: {
type: "string",
enum: ["function", "event", "constructor"],
description: "类型:function(函数)、event(事件)、constructor(构造函数)"
},
inputs: {
type: "array",
description: "输入参数",
items: {
type: "object",
properties: {
name: {
type: "string",
description: "参数名称"
},
type: {
type: "string",
description: "参数类型"
}
}
}
}
}
}
}
}
]
})

配置editor进行suggest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
options={{
minimap: { enabled: false },
lineNumbers: true,
quickSuggestions: true, // 自动补全
autoIndent: true,
automaticLayout: true,
validate: true,
folding: true,
hover: {
enabled: true,
},
suggest: {
insertMode: "insert",
showInlineDetails: true,
showDetails: true,
preview: true,
previewMode: 'prefix',
maxVisibleSuggestions: 12,
},
}}

注意

  1. 如果仅仅只是为了特定的编辑器实现提示,那么需要fileMatch进行限制,否则会引发其它编辑器下针对JSON的提示。

效果

https://static.1991421.cn/2025/2025-03-19-170140.jpeg

https://static.1991421.cn/2025/2025-03-19-170221.jpeg

写在最后

通过上述方法即了解了如何在monaco-editor中实现JSON数据固定类型的代码提示。