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?