【问题标题】:Monaco editor load theme without instance摩纳哥编辑器加载主题没有实例
【发布时间】:2020-09-23 07:24:05
【问题描述】:

我正在创建一个使用 Monaco Editor 的 Web 应用程序。因为这已经加载了,所以我决定也使用 Monaco 来突出显示静态代码块的语法。

基于this answer,我设法为静态代码块添加了语法高亮(添加了元素和类名。

问题是,只有在创建 Monaco 编辑器实例时才会加载相关的 CSS,这发生在不同的页面上。这意味着它仅适用于包含 Monaco 编辑器实例的页面。

我使用下面的 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>
  );
}

如何让 Monaco 在不创建编辑器实例的情况下加载 CSS?

【问题讨论】:

    标签: javascript typescript monaco-editor


    【解决方案1】:

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

    我是这样做的:

    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>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 2018-01-21
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多