You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Monaco Editor主题?代码验证及令牌列表需求

代码可行性分析与调整建议

你的这段自定义主题代码核心逻辑是可行的,但存在几个需要修正的细节:

  1. 避免使用default作为自定义主题名——Monaco内置了同名主题,会导致冲突,建议改为custom-vs-dark这类唯一名称
  2. 移除规则数组最后一个对象末尾的多余逗号,避免语法错误
  3. 补充identifier.type令牌规则,覆盖TypeScript中部分类型标记场景

调整后的可用代码:

monaco.editor.defineTheme('custom-vs-dark', {
    base: 'vs-dark',
    inherit: true,
    rules: [
      {
        token: "identifier",
        foreground: "#9CDCFE" // 变量设为浅蓝色
      },
      {
        token: "identifier.function",
        foreground: "#DCDCAA" // 函数设为黄色
      },
      {
        token: "type",
        foreground: "#1AAFB0" // 类型设为深绿色
      },
      {
        token: "identifier.type",
        foreground: "#1AAFB0" // 补充覆盖TypeScript类型的额外场景
      }
    ],
    colors: {}
});
monaco.editor.setTheme('custom-vs-dark')
JavaScript/TypeScript常用令牌列表

以下是Monaco中JS/TS语法高亮常用的令牌类型,可用于个性化定制:

  • keyword:关键字(如let、const、function、if)
  • identifier:普通变量标识符
  • identifier.function:函数名(含声明、调用场景)
  • identifier.type:TypeScript类型标识符
  • type:TypeScript内置/自定义类型(如string、接口名)
  • string:字符串字面量
  • number:数字字面量
  • comment:普通注释(单行//、多行/* */)
  • comment.doc:JSDoc注释
  • operator:操作符(如+、=、===)
  • punctuation:标点符号(如{、}、,、;)
  • regexp:正则表达式字面量
  • decorator:TypeScript装饰器(如@Component)
  • variable.parameter:函数参数
  • meta:元数据(如对象字面量的键名)

如果需要精准定位某段代码对应的令牌,可在浏览器控制台执行monaco.editor.getModels()[0].getLineTokens(行号),查看目标行的令牌详情。

内容的提问来源于stack exchange,提问作者Tata Choudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:47:09