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. rehype-pretty-code.
Installing Rehype Pretty Code
To add syntax highlighting to your site, install both of these libraries.
shellnpm install rehype-pretty-code shiki
Setting up the syntax highlighter
Next, 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:
tsimport { 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, 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:
tsexport 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.