How to add syntax highlighting to code blocks

While developing my blog one issue I came across is that the code blocks I’ve added to blog posts weren’t highlighted. By this, I mean that all the code in each code block is the same color rather than there being color coding to make the code in the block easier to read.

The below image shows a code block in one of the posts made.

code-block-1.png

Highlight.js

After searching a library to apply code highlighting I came across highlight.js which looked like a popular library to solve this problem.

code-block-2.png

Highlight.js supports 192 languages, you can even create a custom download by selecting the language you want to be supported by doing to their download page.

It also comes with a lot of themes that can be applied to your code blocks too, go to the examples page to select and view themes. Also the CSS files for the themes can be retrieved from the unpkg website.

To install run the following command, the below code block will also be highlighted as the library will have been integrated with the blog.

npm install highlight.js
# OR
bun install highlight.js

Using Highlight.js with Marked

In terms of my blog, it’s an Astro project that uses the Notion JavaScript library to call the Notion API to retrieve page content. This page data is then converted into markdown format, then converted to HTML, and finally output in the Astro template file.

To apply code lighting for my blog I used a library called marked-highlight which is used in conjunction with the marked library to add the code highlighting when the Notion page data is converted to markdown format.

code-block-3.png

To install marked-highlight use the following command.

npm install marked-highlight
# OR
bun install marked-highlight

The below code shows the change to integrate the new marked-highlight library.

const marked = new Marked(
  markedHighlight({
    langPrefix: "hljs language-",
    highlight(code, lang, info) {
      const language = hljs.getLanguage(lang) ? lang : "plaintext";
      return hljs.highlight(code, { language }).value;
    },
  })
);