Highlighting HTML in NextJS with rehype-highlight

I recently tried to highlight the codes in My blogpost with rehype-highlight

Here's the snippets on how I do it

import rehype from 'rehype'
import highlight from 'rehype-highlight'

....

  const reHTML = await rehype()
    .data('settings', { fragment: true })
    .use(highlight)
    .process(post.bodyHTML)

  • post.bodyHTML is just strings of HTML
  • reHTML now becomes html that's annotated with highlight.js's className

now we only need to put some CSS. I use dracula theme

In my nextjs code, I just import the css in pages/_app.js like this

import 'highlight.js/styles/dracula.css'

Real Code

You can find my implemenatations here

Reach me on twitter @muhajirdev
This site is built with NextJS, hosted on Netlify, and uses Github Issues as CMS