簡體   English   中英

摩納哥編輯器加載主題沒有實例

[英]Monaco editor load theme without instance

我正在創建一個使用 Monaco Editor 的 web 應用程序。 因為這已經加載了,所以我決定也使用 Monaco 來突出顯示 static 代碼塊的語法。

基於這個答案,我設法將語法突出顯示添加到 static 代碼塊(添加了元素和 class 名稱。

問題是,相關的 CSS 只有在創建 Monaco 編輯器實例時才會加載,這發生在不同的頁面上。 這意味着它僅適用於包含 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>
  );
}

如何讓摩納哥在不創建編輯器實例的情況下加載 CSS?

受此問題報告的啟發: 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>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM