Tips about how to use highlight.js
While developing GitLink, I needed code highlighting functionality, so I researched highlight.js and discovered some implementation details worth noting.
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
- 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.
- 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. - 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
At the end
These are some issues I encountered while using highlight.js. There might be other considerations, and I welcome any discussion.