Hugo has a built-in syntax highlight that uses Chroma, a library written in go.
As much as I love libraries such as
highlight.js, and even if they have plenty of crazy good options, I decided to drop them.
Permalink to heading You don’t need that. Drop it. You don’t need that. Drop it.
Performances are a common concern. To highlight code, you can use client-side libraries, but server-side can be a significant optimization.
The great news is Hugo provides that.
Permalink to heading How to How to
I give you a sample config. Of course, feel free to make modifications. For example, I don’t use line numbers because I think it’s lame, especially for copy-paste, but that’s just my opinion.
guessSyntax parameter is crucial to me, as I don’t use shortcodes to highlight code, only markdown tags.
You can read the documentation to get all the details.
As a starter, you can add the following in your
[markup.highlight] codeFences = true guessSyntax = true lineNos = false tabWidth = 4 noClasses = false
hugo gen chromastyles --style=xcode > syntax.css
syntax.css to get your styles. Of course, you can choose another predefined stylesheet.
Chroma shares some base code with Pygments, an older library. You get many common settings, which is pretty cool to ease the transition.
Permalink to heading Possible caveats Possible caveats
As far as I know, Chroma seems a little less precise than hyper boosted client-side libraries such as Prism.
I’ve noticed some minor glitches, such as a few inconsistencies with colors. However, that’s tolerably rare.
You won’t get features such as “copy to clipboard”, but that’s not the most complicated feature to code in vanilla js if you have to provide it.
You can read the complete list of supported languages here.
If that’s the same for you, you can safely switch to Chroma highlighting.
Permalink to heading So convenient! So convenient!
Server-side highlighting with Chroma is smooth:
- the transition with Pygments is seamless
- it’s extra-light as you only load CSS
- it supports an extensive range of languages
- there’s an online playground to test predefined styles
Happy Chroma highlighting ;)
I do my best to update all my contents, but keep it mind that "Hugo: light syntax highlight" has been published many months ago.