How to use monaco editor for syntax highlighting?

I had the same problem so I created issue #1171:

  • https://github.com/Microsoft/monaco-editor/issues/1171

and two solutions were provided:

a) Format an existing HTML element:

monaco.editor.colorizeElement(document.getElementById("yourElement"));

Here is a playground link for trying this out live: https://microsoft.github.io/monaco-editor/playground.html#creating-the-editor-syntax-highlighting-for-html-elements

b) Format a text which is not part of any element. This is a more generic approach which returns a Promise:

const code = "source code";
monaco.editor.colorize(code, "javascript")
  .then(html => document.getElementById("yourElement").innerHTML = html);

Documentation:

  • https://microsoft.github.io/monaco-editor/api/modules/monaco.editor.html#colorize

In case someone is still searching, there's currently a declarative syntax highlighter for Monaco Editor, called Monarch