---
title: "Syntax Highlight Code in Markdown Posts"
date: 2022-11-09T13:19:38.000Z
author: Z.SHINCHVEN
tags: [highlight.js, Markdown]
canonical: https://atlassc.net/2022/11/10/syntax-highlight-code-in-markdown-posts
---
I wrote this TypeScript full stack blogging web app for myself serving posts written in [Markdown](https://daringfireball.net/projects/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](https://highlightjs.org/) is a popular syntax highlighter, and it supports [over 200 languages](https://highlightjs.org/static/demo/).

Here's how I do it...

## Transform Markdown to HTML with highlight.js CSS Class

To do so, I used the following packages:

- [showdown](https://www.npmjs.com/package/showdown) - The Markdown parser I use to transform Markdown to HTML. 
- [showdown-highlight](https://www.npmjs.com/package/showdown-highlight) - An extension for showdown to support syntax highlight.

```typescript
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](https://github.com/showdownjs/showdown/wiki/extensions) for `showdown`.

## Import highlight.js CSS in My React App

There are a bunch of [styles provided by highlight.js](https://highlightjs.org/static/demo/), choose one you like.

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

It's done.
