Monaco编辑器中如何自定义背景颜色?

12

通过查看Monaco示例和类型定义,似乎可以通过defineTheme API配置主题。我正在尝试将VSCode主题应用于Monaco实例,并且不知道如何设置背景颜色(对整个编辑器而不仅仅是对标记)。

规则被定义为具有这种形状的对象数组:

IThemeRule {
    token: string;
    foreground?: string;
    background?: string;
    fontStyle?: string;
}

设置编辑器背景应该使用什么token

更一般地说,有没有一种好的方法可以将这个主题应用于 Monaco 实例,而不需要从 VSCode 源代码中删除主题解析逻辑?在尝试快速删除逻辑后,似乎一个简单的自定义解析器(即将 JSON 主题定义解析为平面列表的IThemeRule)是更好的选择。

3个回答

13

您可以定义自己的主题,并在颜色选项中更改editor.background

monaco.editor.defineTheme('my-dark', {
        ...,
        colors: {
          "editor.background": '#394555'
        }
      });

10
您可以像这样定义您的主题。
const theme = {
  base: 'vs', 
  inherit: true,
  rules: [
    { token: 'custom-info', foreground: 'a3a7a9', background: 'ffffff' },
    { token: 'custom-error', foreground: 'ee4444' },
    { token: 'custom-notice', foreground: '1055af' },
    { token: 'custom-date', foreground: '20aa20' },
  ]
}

然后像这样应用它

monaco.editor.defineTheme('myTheme', theme)

var editor = monaco.editor.create(document.getElementById('container'), {
    value: getCode(),
    language: 'myCustomLanguage',
    theme: 'myTheme'
});

2
OP特别要求设置编辑器背景,而不是每个标记的背景颜色。此外,标记背景颜色似乎存在一个错误,目前无法以这种方式设置。Zanecat给出了正确的答案。 - perkrlsn
1
顺便说一句,今天我遇到了一个可能的错误,即使已经设置了“rules”,我还被迫设置一个虚拟的colors: {}:https://github.com/cirosantilli/cirosantilli.github.io/issues/82 失败并显示“Cannot read properties of undefined (reading 'editor.foreground')”。 - Ciro Santilli OurBigBook.com

1
import Editor, { loader } from '@monaco-editor/react';

loader.init().then((monaco) => {
    monaco.editor.defineTheme('myTheme', {
        base: 'vs',
        inherit: true,
        rules: [],
        colors: {
            'editor.background': '#efefef',
        },
    });
});

然后:

<Editor theme='myTheme' ... />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接