avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Syntax Highlight Code in Markdown Posts

Wed Nov 09 2022

I wrote this TypeScript full stack blogging web app for myself serving posts written in Markdown.

As a programmer, I write a lot of code in my posts, and I want to syntax highlight them for better readability.

highlight.js is a popular syntax highlighter, and it supports over 200 languages.

Here's how I do it…

Transform Markdown to HTML with highlight.js CSS Class

To do so, I used the following packages:

  • showdown - The Markdown parser I use to transform Markdown to HTML.
  • showdown-highlight - An extension for showdown to support syntax highlight.
import showdown from 'showdown';
import showdownHighlight from 'showdown-highlight';

// Create showdown converter
export const showdownConverter = new showdown.Converter({
  tables: true,
  // Configure extensions
  extensions: [showdownHighlight({
    pre: true,
    auto_detection: true,
  })],
});

// The markdown string with code block
const markdown = '```typescript\nconst a = 1;\n```';

// Now I have the HTML string with highlight.js CSS class in pre tag.
const html = showdownConverter.makeHtml(markdown);

Others extensions for showdown.

Import highlight.js CSS in My React App

There are a bunch of styles provided by highlight.js, choose one you like.

import 'highlight.js/styles/github.css';

It's done.