Monaco-Editor Implementation of Syntax Highlighting

Nov 7, 2024 · 2 min read · 246 Words · -Views -Comments · Programming
Monaco JavaScript Editor 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

You need to configure the language to implement syntax highlighting in Monaco Editor. Here, we introduce the related operations.

https://static.1991421.cn/2024/2024-11-07-231727.jpeg

Set Language

If setting the language during initialization, the operation is as follows:

monaco.create(el, {
...
language: 'sol',
      })

If setting the language dynamically:

const model = editor.getModel();
monaco.editor.setModelLanguage(model, 'json');

Built-in Language Support in Monaco

Which languages support syntax highlighting? You can confirm this in several ways.

  1. Retrieve in the program.
const languages = monaco.languages.getLanguages();

Note: The number of languages retrieved by this method includes custom-registered languages in the application, not limited to built-in languages only.

https://static.1991421.cn/2024/2024-11-07-230212.jpeg

  1. Visit https://microsoft.github.io/monaco-editor/ and check the language dropdown options directly.

    https://static.1991421.cn/2024/2024-11-07-230736.jpeg

  2. Directly visit the npm package monaco-editor/esm/vs/basic-languages, where the built-in languages are registered.

https://static.1991421.cn/2024/2024-11-07-231538.jpeg

Note that each folder name does not necessarily represent the language name; the ID defines the language name.

https://static.1991421.cn/2024/2024-11-07-232154.jpeg

Pack Language Files as Needed

Monaco Editor supports many languages by default. However, if you package them all, the file may be too large, so you can pack languages as needed.

  1. To import Monaco Editor:
# Correct method
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

# Incorrect method
import * as monaco from 'monaco-editor';

The webpack configuration is as follows:

new MonacoWebpackPlugin({
      filename: 'monaco_[name].worker.[contenthash].js',
      languages: ['json', 'solidity', 'sql'],
    })

Note: If you find that all languages are still packaged after configuring the languages in webpack, it is usually due to an incorrect import method for Monaco.

At the end

Now, we know how to configure languages in actual projects to achieve syntax highlighting.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover