Nono.MA

How to highlight code with highlight.js

APRIL 6, 2022

My site parses Markdown posts into HTML and code blocks are syntax-highlighted with the highlight.js JavaScript library.

How does highlight.js work?

In a nutshell, Markdown code blocks—the content between a pair of three backticks—are parsed into <pre><code> HTML blocks.

If we take this Markdown input.

```
console.log(`Hello, highlight.js!`);
console.log(`Formatting Markdown code blocks!`);
const add = (a: number, b: number) => a + b
add(2, 3) // Returns 5
```

The Markdown parser converts it into a <pre><code> HTML block.

<pre><code>console.log(`Hello, highlight.js!`);
console.log(`Formatting Markdown code blocks!`);
const add = (a: number, b: number) => a + b
add(2, 3) // Returns 5
</code></pre>

Which is then highlighted by highlight.js.

console.log(`Hello, highlight.js!`);
console.log(`Formatting Markdown code blocks!`);
const add = (a: number, b: number) => a + b
add(2, 3) // Returns 5

How can you use highlight.js on your site?

This is all the HTML code you really need.

  • The HTML code block
  • Loading highlight.js
  • Optionally loading a highlight.js CSS style
  • Initialize highlight.js
<!-- Code block -->
<pre><code>console.log(`Hello, highlight.js!`);
console.log(`Formatting Markdown code blocks!`);
const add = (a: number, b: number) => a + b
add(2, 3) // Returns 5
</code></pre>

<!-- Load highlight.js from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/highlight.min.js"></script>

<!-- Optionally load a template from a CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/atom-one-light.min.css" integrity="sha512-o5v54Kh5PH0dgnf9ei0L+vMRsbm5fvIvnR/XkrZZjN4mqdaeH7PW66tumBoQVIaKNVrLCZiBEfHzRY4JJSMK/Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<!-- Initialize highlight.js -->
<script>hljs.initHighlightingOnLoad();</script>

How can you add dark mode support to highlight.js?

In my case, I create custom templates or use the ones provided by highlight.js. The only tweak to support the system's appearance—light and dark mode—is to use CSS's prefers-color-scheme to target whether the user has the system's dark mode enabled.

/* highligh-styles.js */

/* Light mode highlight.js theme goes here */

@media screen and (prefers-color-scheme: dark) {
  /* Dark mode highlight.js theme goes here */
}

Thanks to Nino. This post is a reply to his question on Twitter.

BlogCodeJavascriptCss