我正在创建一个使用Monaco Editor的网络应用程序。因为已经加载了该代码,所以我决定也将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?
答案 0 :(得分: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>
);
};