简体   繁体   English

摩纳哥编辑器加载主题没有实例

[英]Monaco editor load theme without instance

I'm creating a web application which uses Monaco Editor.我正在创建一个使用 Monaco Editor 的 web 应用程序。 Because this is already loaded, I decided to also use Monaco for syntax highlighting of static code blocks.因为这已经加载了,所以我决定也使用 Monaco 来突出显示 static 代码块的语法。

Based on this answer , I managed to add syntax highlighting to static code blocks (the elements and class names are added.基于这个答案,我设法将语法突出显示添加到 static 代码块(添加了元素和 class 名称。

The problem is, the related CSS is only loaded if a Monaco editor instance is created, which happens on a different page.问题是,相关的 CSS 只有在创建 Monaco 编辑器实例时才会加载,这发生在不同的页面上。 This means that it only works if a page that contains a Monaco editor instance.这意味着它仅适用于包含 Monaco 编辑器实例的页面。

I use the following React component to add syntax highlighting.我使用以下 React 组件来添加语法高亮。

import { editor } from 'monaco-editor';
import React, { ReactElement, useEffect, useRef } from 'react';

interface CodeBlockProps {
  /**
   * The code to render.
   */
  code: string;

  /**
   * The language to use for highlighting the code.
   */
  language: string;
}

/**
 * Render a code block using syntax highlighting based on Monaco editor.
 */
export default function CodeBlock({ code, language }: CodeBlockProps): ReactElement {
  const ref = useRef<HTMLPreElement>();

  useEffect(() => {
    if (language) {
      editor.colorizeElement(ref.current, { theme: 'vs' });
    }
  }, [language]);

  return (
    <pre ref={ref} data-lang={language}>
      {code}
    </pre>
  );
}

How do I make Monaco load the CSS without creating an editor instance?如何让摩纳哥在不创建编辑器实例的情况下加载 CSS?

Inspired by this issue report: https://github.com/microsoft/monaco-editor/issues/1828受此问题报告的启发: https://github.com/microsoft/monaco-editor/issues/1828

I did it like this:我是这样做的:

import React from 'react';
import * as MonacoEditorApi from 'monaco-editor/esm/vs/editor/editor.api';
const { StaticServices } = require('monaco-editor/esm/vs/editor/standalone/browser/standaloneServices');
const { StandaloneThemeServiceImpl } = require('monaco-editor/esm/vs/editor/standalone/browser/standaloneThemeServiceImpl');

export const Viewer: React.FC<{ source: string }> = (props) => {
  // use a callback ref to get notified when the element has mounted
  const viewerRef = (ref: HTMLPreElement) => {
    if (ref) {
      MonacoEditorApi.editor.colorizeElement(ref, { theme: 'vs' });
      const themeService: typeof StandaloneThemeServiceImpl = StaticServices.standaloneThemeService.get();
      themeService.registerEditorContainer(ref);
    }
  };
  return (
    <pre data-lang="yaml" ref={viewerRef}>
      {props.source}
    </pre>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM