Next MDX
HomeDocumentationGuidesGitHub
/
,

Syntax Highlighting

Add syntax highlighting using Prism or highlight.js


Prism

To add syntax highlighting using Prism, we are going to use a rehype plugin.

Install dependencies

npm install @mapbox/rehype-prism prismjs

Enable plugin in mdxOptions.

Next, enable the @mapbox/rehype-prism plugin by passing it to mdxOptions in getStaticProps:

pages/blog/[...slug].tsx
...
export async function getStaticProps(context) {
const post = await getMdxNode("post", context, {
mdxOptions: {
rehypePlugins: [require("@mapbox/rehype-prism")],
},
})
if (!post) {
return {
notFound: true,
}
}
return {
props: {
post,
},
}
}

Import CSS.

You can now import a Prism theme in pages/blog/[...slug].tsx:

pages/blog/[...slug].tsx
import { useHydrate } from "next-mdx/client"
import { getMdxNode, getMdxPaths } from "next-mdx/server"
import "prismjs/themes/prism-okaidia.css"

You can find more theme options here.

Highlight.js

To add syntax highlighting using highlight.js, add the rehype-highlight rehype plugin.

Install dependencies

npm install rehype-highlight highlight.js

Enable plugin in mdxOptions.

Next, enable the rehype-highlight plugin by passing it to mdxOptions in getStaticProps:

pages/blog/[...slug].tsx
...
export async function getStaticProps(context) {
const post = await getMdxNode("post", context, {
mdxOptions: {
rehypePlugins: [require("rehype-highlight")],
},
})
if (!post) {
return {
notFound: true,
}
}
return {
props: {
post,
},
}
}

Import CSS.

You can now import a highlight.js theme in pages/blog/[...slug].tsx:

pages/blog/[...slug].tsx
import { useHydrate } from "next-mdx/client"
import { getMdxNode, getMdxPaths } from "next-mdx/server"
import "highlight.js/styles/atom-one-dark.css"

You can find more theme options for highlight.js here.

Table of ContentsgetMdxPaths

© 2021 Next MDX - Project maintained by @arshadcn.

HomeDocumentationGuidesGitHub