After a bit of research I realised that Hugo natively supports source code syntax highlighting via a tool known as Chroma. One of the biggest advantages with this approach is that the highlighting happens at compile-time: Hugo will turn your code fences into a tree of static HTML - essentially, a set of nested
<span>s, each containing inline styles to beautify the code snippet. This is a very appealing approach, and fits in well with the concept of a static site generator, where the output is the HTML and CSS/styles that the end user will view.
Supporting Chroma is as simple as adding the following to your
pygmentsCodeFences = true # Enable triple backtick 'code fence' markdown pygmentsUseClasses = false # Add inline styles, no need to compile extra CSS
You can now add code using the triple backtick ‘code fence’ markdown syntax, as follows:
``` jsx import React from 'react'; const App = () => ( <div class="app"></div> ); export default App; ```
The text after the triple backtick governs the code language, which is used to determine the keywords that should be highlighted. In this case, I’m using the
The markdown above will produce the following output:
import React from 'react'; const App = () => ( <div class="app"></div> ); export default App;
You can also customise the colour scheme used for highlighting the keywords by adding the following to your
pygmentsStyle = "friendly" # Change this to the theme you want
A full list of supported themes can be found here.
If you have set up your site to be automatically built and deployed to Netlify as outlined on the Hugo site, you may find that your freshly deployed site has not correctly parsed code blocks into the necessary HTML, instead outputting the text as-is.
The reason for this is that Netlify (by default) uses a very old version of Hugo to compile your code (v0.17) which does not support these code blocks. To remedy:
HUGO_VERSIONand set it to the latest version of Hugo (at the time of writing, this is 0.49).
The next time you push a new commit, your site should be built and deployed correctly by Netlify.
Hugo makes syntax highlighting your code snippets a breeze!