Tips about how to use highlight.js

A comprehensive guide on using highlight.js, covering CDN integration, language registration, auto-detection, and line number display features.

Mar 25, 2025 · 1 min read · 193 Words · -Views -Comments · Digital Life
Highlight.js Code Highlighting 🇨🇳 阅读中文版
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.

While developing GitLink, I needed code highlighting functionality, so I researched highlight.js and discovered some implementation details worth noting.

https://static.1991421.cn/2025/2025-03-25-235551.jpeg

Import highlight.js

For web pages requiring CDN import or direct src import, you should not use highlight.js resources directly, but rather use highlightjs/cdn-release.

For projects involving build tools, you should use the npm package of highlight.js.

Language Registration

  1. Importing highlight.js doesn’t automatically register all languages supported by highlight.js. If you want to register all languages, you need to import and register them manually.
  2. Taking the highlight.js npm package as an example, in /highlight.js/es/languages/, you can see all language files. To register all languages, you need to import all these language files.
  3. Besides official languages, you can also register custom languages. For example, some language packages provided in the official repo, such as highlightjs-4d

Auto highlight

In addition to the highlight method, there’s also highlightAuto for use when the language is uncertain.

Display Line Numbers

highlight.js doesn’t natively support line number display. You need to use third-party plugins for this functionality, such as highlightjs-line-numbers.js

Final Thoughts

These are some issues I encountered while using highlight.js. There might be other considerations, and I welcome any discussion.

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