mdx-prism
This is a fork of @mapbox/rehype-prism that adds line highlighting capabilities, e.g.:
rehype plugin to highlight code blocks in HTML with Prism.
(If you would like to highlight code blocks with highlight.js, instead, check out rehype-highlight.)
Best suited for usage in Node. If you would like to perform syntax highlighting in the browser, you should look into less heavy ways to use refractor.
Installation
npm install mdx-prism
API
rehype().use(rehypePrism, [options])
Syntax highlights pre > code
.
Under the hood, it uses refractor, which is a virtual version of Prism.
The code language is configured by setting a language-{name}
class on the <code>
element.
You can use any language supported by refractor.
If no language-{name}
class is found on a <code>
element, it will be skipped.
options
options.ignoreMissing
Type: boolean
.
Default: false
.
By default, if {name}
does not correspond to a language supported by refractor an error will be thrown.
If you would like to silently skip <code>
elements with invalid languages, set this option to true
.
Usage
Use this package as a rehype plugin.
Some examples of how you might do that:
const rehype = ;const mdxPrism = ; ;
const unified = ;const rehypeParse = ;const mdxPrism = ; ;
If you'd like to get syntax highlighting in Markdown, parse the Markdown (with remark-parse), convert it to rehype, then use this plugin.
const unified = ;const remarkParse = ;const remarkRehype = ;const mdxPrism = ; ;
FAQ
Why does mdx-prism copy the language-
class to the <pre>
tag?
Prism recommends adding the language-
class to the <code>
tag like this:
p { color: red }
It bases this recommendation on the HTML5 spec. However, an undocumented behavior of their JavaScript is that, in the process of highlighting the code, they also copy the language-
class to the <pre>
tag:
p { color: red }
This resulted in many Prism themes relying on this behavior by using CSS selectors like pre[class*="language-"]
. So in order for people using mdx-prism to get the most out of these themes, we decided to do the same.