Render Markdown To HTML Using Node.js With Syntax Highlighting

Inspiration

I wanted a simplistic blogging experience and being a developer, using markdown for these blog posts just seemed right.

The Approach

Pretty straightforward, use a couple of libraries, not much to it.

  1. Turn our markdown file into HTML
  2. Apply syntax highlighting to code blocks

Libraries

Markdown to HTML

We'll be using the following markdown file for this demo.

# Hello World

Hello World in **Javascript**

```javascript
console.log('Hello World!');
```

With the library markdown-it, there's not much for us to do to render this into HTML.

import Markdown from 'markdown-it';

const md = Markdown();
const html = md.render(content);

console.log(html);

And if we run the code above, we'll get the following.

1<h1>Hello World</h1>
2<p>Hello World in <strong>Javascript</strong></p>
3<pre>
4 <code class="language-javascript">
5 console.log('Hello World!');
6 </code>
7</pre>

Nice! But if you look at line number 5. You'll notice that it's just one long dull text. We need to break it apart and highlight it just like our code editors.

Syntax Highlighting

For easier readability, we need to highlight specific groups of text. Luckily there's a neat little library that does this for us already, highlight.js

Markdown-it has an option highlight that we can easily use to hook up.

import hljs from 'highlight.js';
import Markdown from 'markdown-it';

const md = Markdown({
  highlight: (
    str: string,
    lang: string,
  ) => {
    const code = lang && hljs.getLanguage(lang)
      ? hljs.highlight(str, {
          language: lang,
          ignoreIllegals: true,
        }).value
      : md.utils.escapeHtml(str);
    return `<pre class="hljs"><code>${code}</code></pre>`;
  },
});

Now if we call md.render() on the markdown text again, we get this.

<h1>Hello World</h1>
<p>Hello World in <strong>Javascript</strong></p>
<pre class="hljs">
  <code>
    <span class="hljs-built_in">console</span>
    .log(
    <span class="hljs-string">&#x27;Hello World!&#x27;</span>
    );
  </code>
</pre>

Specific classes are added around the built-in function console and the string Hello World.

You can use themes from highlight.js here or style it yourself.

Currently, I'm just using the Stack Overflow light theme from highlight.js.

import 'highlight.js/styles/stackoverflow-light.css';

Next

As I was writing this, I realized I wanted to reference a specific line number in the code block (Line 5). So I thought it'll be interesting to build it myself. The post is up if you are interested, How To Add line Numbers To Markdown Code Blocks