Reputation: 791
I'm trying to highlight my code syntax using next-mdx-remote
in my Nextjs based page. I'm getting my markdown format from graphcms
and rendering it like this :
import { serialize } from "next-mdx-remote/serialize"
import { MDXRemote } from "next-mdx-remote"
import rehypeHighlight from "rehype-highlight"
export async function getStaticProps({ params }: any) {
const data = await getPostDetail(params?.slug)
const source = data?.content?.markdown
const mdxSource = await serialize(source, {
mdxOptions: { rehypePlugins: [rehypeHighlight] },
})
return {
props: {
posts: data,
mdxSource: mdxSource,
},
}
}
function Post({mdxSource}){
return(
<MDXRemote {...mdxSource} />
)
}
Unfortunately, the code blocks gets rendered like normal text fields and doesn't do anything.
I'm not sure what I'm missing here, the official documentation doesn't clarify this as well
Upvotes: 7
Views: 4990
Reputation: 965
rehype-highlight
on its own only adds css classnames to your html code blocks. You then need to import a highlight.js stylesheet to style these blocks.
You can download them from here and then import them into your page like this:
import "@/styles/highlight-js/github-dark.css"
A full tutorial can be found here: https://gaudion.dev/blog/mdx-syntax-highlighting
Upvotes: 1
Reputation: 1832
You just need to add the highlight style in your header
import { serialize } from "next-mdx-remote/serialize"
import { MDXRemote } from "next-mdx-remote"
import rehypeHighlight from "rehype-highlight"
export async function getStaticProps({ params }: any) {
const data = await getPostDetail(params?.slug)
const source = data?.content?.markdown
const mdxSource = await serialize(source, {
mdxOptions: { rehypePlugins: [rehypeHighlight] },
})
return {
props: {
posts: data,
mdxSource: mdxSource,
},
}
}
function Post({mdxSource}){
return(
<>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/dark.css"></link>
<MDXRemote {...mdxSource} />
</>
)
}
And to enhance your code you can add this style inside the Head
element or inside the document file which allows you to inject extra components styles, SEO,... etc.
_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link
rel="stylesheet"
href="https://unpkg.com/dracula-prism/dist/css/dracula-prism.css"
></link>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Upvotes: 0
Reputation: 1940
According to mdx docs you want to include the below link somewhere in your header.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/github-dark.min.css"></link>
let me know if it doesn't work. it works for me at the least.
Upvotes: 4
Reputation: 21
I think you need to add some css? For example
import "highlight.js/styles/atom-one-dark.css";
Upvotes: 2