Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do syntax highlighting on Next.js markdown blog

I'm using Next.js for my blog and I'm storing my blogs in markdown files and converting those files to string and then into HTML using Greymatter. My code blocks break down into <pre><code class="language-whatever"> and no matter what I do, I can't get syntax highlight to occur.

I've tried adding highlight.js through npm, downloading files from highlight.js and prism, using their cdn's, and nothing is really working.

Is there anybody who has experience setting up syntax highlighting on a markdown blog using Next.js? An example or any advice would be great! Thanks.

like image 218
Jimmy McBride Avatar asked May 11 '20 04:05

Jimmy McBride


2 Answers

I figured it out! I used react-syntax-highlighter in combination with react-markdown. I got some code snippets from this blog with how to parse the code snippets and pass then through the syntax highlighter.

Here's my repo, if you want to check out my solution.

I was using marked to convert my markdown to an HTML string which was blocking the highlighting for happening. Once I pulled my markdown content out of marked dependencies and passed in the gray-matter.content to my ReactMarkdown it worked perfectly.

...Well, maybe not perfectly...

There was some weird stuff happening when I was trying to use color themes. I ended up having the pull the theme I wanted out of the node modules and placed it in my root and called it from there and it was perfectly fine. A little hacky, but it works!

like image 200
Jimmy McBride Avatar answered Sep 25 '22 21:09

Jimmy McBride


Here is how I got syntax highlighting working in Next.js https://thetombomb.com/posts/adding-code-snippets-to-static-markdown-in-Next%20js

I was originally using greymatter since I built the app following the Next.js starter app project. I had to move over to using react-markdown with react-syntax-highlighter to get everything working.

like image 33
tdesmond Avatar answered Sep 25 '22 21:09

tdesmond