I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks.
Following guidance from this source, I successfully implemented syntax highlighting within static code blocks by adding the necessary elements and class names.
An issue I encountered is that the CSS related to this feature only loads when a Monaco editor instance is initialized on a separate page. Consequently, syntax highlighting only functions if a page contains a Monaco editor instance.
To address this challenge, I utilized the following React component for implementing syntax highlighting:
import { editor } from 'monaco-editor';
import React, { ReactElement, useEffect, useRef } from 'react';
interface CodeBlockProps {
/**
* The code snippet to display.
*/
code: string;
/**
* The programming language used for code highlighting.
*/
language: string;
}
/**
* A component to display code with syntax highlighting using 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>
);
}
I'm seeking a solution to prompt Monaco to load the required CSS without necessitating the creation of an editor instance. Any insights or recommendations would be greatly appreciated.