This content originally appeared on DEV Community and was authored by Julien Maury
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.
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.
Instead of loading both CSS and JavaScript, I only need CSS. Fewer javaScript, fewer bytes, and, above all, with pretty much the same results.
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.
The 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 config.toml
file:
[markup.highlight]
codeFences = true
guessSyntax = true
lineNos = false
tabWidth = 4
noClasses = false
Then run:
hugo gen chromastyles --style=xcode > syntax.css
And load 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.
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.
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 ;)
This content originally appeared on DEV Community and was authored by Julien Maury
Julien Maury | Sciencx (2021-04-16T12:09:04+00:00) Hugo: light syntax highlight. Retrieved from https://www.scien.cx/2021/04/16/hugo-light-syntax-highlight/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.