I'm creating a web application which uses Monaco Editor. Because this is already loaded, I decided to also use Monaco for syntax highlighting of static code blocks.
Based on this answer , I managed to add syntax highlighting to static code blocks (the elements and class names are added.
The problem is, the related CSS is only loaded if a Monaco editor instance is created, which happens on a different page. This means that it only works if a page that contains a Monaco editor instance.
I use the following React component to add syntax highlighting.
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?
Inspired by this issue report: 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>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.