Syntax highlighting
Syntax highlighting is a useful feature that helps make code examples in your blog or website more readable and visually appealing. In this post, we will look at how to add syntax highlighting to a Nextjs site. https://github.com/atomiks/rehype-pretty-code.
Installing Rehype Pretty Code
To add syntax highlighting to your site, you will need to install both of these libraries.
npm install rehype-pretty-code shiki
Setting up the syntax highlighter
Next, you will need to configure rehype-pretty-code
to use shiki as the syntax
highlighter. To do this, create a file called rehype-pretty-code-options.ts
and add the following code:
import { Options } from 'rehype-pretty-code';
export const rehypePrettyCodeOptions: Partial<Options> = {
theme: {
dark: 'dark-plus',
light: 'light-plus',
},
};
This sets up the options for plugin, including the theme to use for syntax highlighting. You can choose from a variety of built-in themes, or import some vscode theme and parse them.
Using the syntax highlighter
To use the syntax highlighter, you will need to add it to your site's build
process. When using content layer
library, you can add the syntax highlighter
by adding the following code to your contentlayer.config.js file:
export default makeSource({
contentDirPath: 'contents',
documentTypes: [Post, About],
date: {
timezone: 'Asia/Jakarta',
},
mdx: {
rehypePlugins: [[rehypePrettyCode, rehypePrettyCodeOptions]],
},
});
This will add the syntax highlighter as a rehype plugin, which will automatically highlight code blocks in your MDX files.
That's it! You should now have syntax highlighting set up on your site. With just a few simple steps, you can make your code examples more readable and visually appealing for your readers.