Add syntax highlighting to the Next.js markdown blog tutorial
| Next.js, website
If you're like me you walked yourself through the Next.js tutorial on how to build a blog -- Create a Next.js App. And at some point you found yourself wondering how to get that sweet syntax highlight that everyone seems to have on their blogs and tutorials.
Basically you just need to:
- Use 'unified' to call 'remark' and a new helper.
- add 'highlight.js'.
- add the CSS to the blog template.
So [id].tsx should contain the block below:
<Head>
<title>{postData.title}</title>
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.0.1/build/styles/default.min.css"></link>
</Head>
Or even better you can simply import the css file:
import 'highlight.js/styles/paraiso-light.css';
And posts#getPostData() should look something like this:
import unified from 'unified'
import markdown from 'remark-parse'
import remark2rehype from 'remark-rehype'
import html from 'rehype-stringify'
const highlight = require('rehype-highlight')
export async function getPostData(id: string): Promise<PostData> {
const fullPath = path.join(postsDirectory, `${id}.md`)
const fileContents = fs.readFileSync(fullPath, 'utf8')
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents)
// Use remark (via 'unified') to convert markdown into HTML string
const processedContent = await unified()
.use(markdown)
.use(remark2rehype)
.use(highlight)
.use(html)
.process(matterResult.content)
const contentHtml = processedContent.toString()
// Combine the data with the id and contentHtml
return {
id,
contentHtml,
...matterResult.data
}
}
Thanks to the following writeups that helped guide me down the path: