5

Hugo: light syntax highlight

 3 years ago
source link: https://dev.to/jmau111/hugo-light-syntax-highlight-5496
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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
Enter fullscreen modeExit fullscreen mode

Then run:

hugo gen chromastyles --style=xcode > syntax.css
Enter fullscreen modeExit fullscreen mode

And load syntax.css to get your styles. Of course, you can choose another predefined stylesheet.

See all predefined styles

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:

Happy Chroma highlighting ;)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK