如何让VSCode颜色选择器对JSON文件中任意键的HEX色值生效
方案1:使用JSON Schema的patternProperties匹配任意键名
JSON Schema 提供patternProperties配置项,可以通过正则匹配所有属性键名,无需逐个枚举,配置示例如下:
{ "type": "object", "patternProperties": { // 正则.*匹配所有属性键名 ".*": { "type": "string", "format": "color" } } }
如果你的主题配置存在多层嵌套结构,可以递归引用schema实现全层级颜色识别:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "patternProperties": { ".*": { "anyOf": [ // 字符串类型默认识别为颜色 { "type": "string", "format": "color" }, // 对象类型递归应用当前schema规则 { "$ref": "#" } ] } } }
如果需要排除特定键(比如主题名称、版本号这类非颜色属性),只需在properties中单独声明这些键的规则,优先级会高于patternProperties:
{ "type": "object", "properties": { "name": { "type": "string" }, "version": { "type": "string" }, "author": { "type": "string" } }, "patternProperties": { ".*": { "anyOf": [ { "type": "string", "format": "color" }, { "$ref": "#" } ] } } }
方案2:直接开启VSCode全局颜色装饰器
无需编写JSON Schema,直接修改VSCode配置即可让所有JSON/JSONC文件中的合法HEX色值自动显示颜色选择器:
- 打开VSCode设置页,搜索
colorDecorators - 勾选
JSON > Color Decorators: Enable和JSONC > Color Decorators: Enable选项 - 如果你的主题配置文件是自定义后缀,需要先关联到JSON语言,在
settings.json中添加:
"files.associations": { "*.your-theme-suffix": "json" }
内容的提问来源于stack exchange,提问作者RATIU5
相关产品推荐
相关产品推荐

