Val-istar-Guo / rehype-prism

The unified plugin used to highlight code block in html with Prism
MIT License
12 stars 1 forks source link

logo

version downloads dependencies license Codecov

The unified plugin used to highlight code block in html with Prism.

Usage

This package is ESM only. unified >= 10 is needed to use it. If running on the server side, NodeJS needs to be greater than 12

import { unified } from "unified";
import rehype from "rehype";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypePrism from "rehype-prism";
import rehypeStringify from "rehype-stringify";

// you have to load css manual
import "prismjs/themes/prism-coy.css";
import "prismjs/plugins/line-numbers/prism-line-numbers.css";

// load languages manual
// import 'prismjs/components/prism-{language}'
import "prismjs/components/prism-go";
import "prismjs/components/prism-java";
import "prismjs/components/prism-python";

// parse markdown to html
unified()
  .use(remarkParse)
  .use(remarkRehype)
  // it should be after rehype
  .use(rehypePrism, { plugins: ["line-numbers"] })
  .use(rehypeStringify)
  .parse(/* markdown string */);
// .processSync(/* markdown string */)

// parse code block in html string
rehype().use(rehypePrism).use(rehypeStringify).parse(/* html string */);
// .processSync(/* html string */)

Server Side Render

PrismJS will auto highlight all code at pre code after browser document loaded.

Disabled prism autoHighlight before import 'rehype-prism'. there are two way to do this:

Some plugins will not work. Because it's only work in browser.

Load Plugins

The names to use can be found here.

Plugins Reimplemented By rehype-prism

The table list plugins that cannot running on the server side. Therefor it has been re-implemented by rehype-prism.

Plugin Name
line-numbers
toolbar
copy-to-clipboard

I haven't tested all prism plugins. If there are another plugins not work, submit issue on github.

Load More Languages

Load Themes

See More

shiki is another code highlight tools that support unified. I recommend you try it. It's new, but better suited for modern front-end projects than Prismjs.

This does not mean that I will give up maintaining this library. If you need this library and have any issue, let me know it.

Contributing & Development

If there is any doubt, it is very welcome to discuss the issue together.