Monaco-Editor Implementation of Syntax Highlighting

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:

1
2
3
4
monaco.create(el, {
...
language: 'sol',
})

If setting the language dynamically:

1
2
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.
1
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:
1
2
3
4
5
# 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:

1
2
3
4
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.