Every code block on this page goes through the setup this post describes, so the page also works as a test page when the theme or the stylesheet changes. Open DevTools on any block to see the data attributes covered below.
rehype-pretty-code is a rehype plugin that highlights code in Markdown and MDX. It is built on Shiki, which uses TextMate grammars and themes, the same engine VS Code uses for syntax highlighting. A TypeScript snippet on a post gets the token colors it would get in VS Code with the same theme.
On this blog the plugin runs inside Velite, which compiles the MDX posts when next dev or next build starts. Highlighting happens once, at build time. The browser receives HTML with the colors already in it, and no highlighter code ships to the reader. Velite's docs recommend build-time highlighting "because it is faster and more stable".
How the pieces connect
There are three moving parts:
next.config.mjsstarts a Velite build when you runnext devornext build. The pattern comes from the Velite Next.js guide, which explains that its Webpack plugin does not work correctly once Turbopack is enabled.- Velite compiles every
content/blog/*.mdxfile with the rehype plugins listed invelite.config.tsand writes each post body to.veliteas a function-body string. - The post page turns that string back into a React component with the JSX runtime and renders it inside a
prosearticle.
The plugin needs Shiki as a peer dependency, so install both:
bun add rehype-pretty-code shikiThe docs page still says the plugin supports Shiki ^1.0.0, but the package.json of version 0.14.6 accepts Shiki 1 through 4.
Here is a trimmed example of a Velite config with the plugin wired in. The options object is where the decisions from the rest of this post end up.
import { defineConfig } from "velite";
import rehypeSlug from "rehype-slug";
import rehypePrettyCode, { type Options } from "rehype-pretty-code";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
const prettyCode: Options = {
theme: "github-dark",
keepBackground: true,
defaultLang: { block: "plaintext" },
};
export default defineConfig({
// root, output and collections omitted
mdx: {
rehypePlugins: [
rehypeSlug,
[rehypePrettyCode, prettyCode],
[rehypeAutolinkHeadings, { behavior: "wrap" }],
],
},
});Velite has separate markdown and mdx option blocks, and fields defined with s.mdx() only read the mdx one. The Velite code highlighting guide shows its plugins under markdown, with a comment telling you to switch to mdx for MDX content. If the plugins sit in the wrong block, the posts still build, just without highlighting.
What the plugin outputs
rehype-pretty-code ships no CSS. Its docs call it unstyled: it adds data attributes and leaves the styling to you. This is the HTML it produces with theme: "github-dark" and the other options at their defaults, for a block with a title, line numbers, one highlighted line and one highlighted word. I reformatted it and removed the per-token color spans:
<figure data-rehype-pretty-code-figure>
<figcaption data-rehype-pretty-code-title data-language="ts" data-theme="github-dark">
lib/format.ts
</figcaption>
<pre style="background-color:#24292e;color:#e1e4e8" tabindex="0" data-language="ts" data-theme="github-dark">
<code data-line-numbers data-line-numbers-max-digits="1" data-language="ts" data-theme="github-dark" style="display: grid;">
<span data-line>export function formatPrice(<mark data-highlighted-chars>amount</mark>: number) {</span>
<span data-line data-highlighted-line> return new Intl.NumberFormat("pl-PL").format(<mark data-highlighted-chars>amount</mark>);</span>
<span data-line>}</span>
</code>
</pre>
</figure>Several details in there affect styling:
- The block sits in a
figurewithdata-rehype-pretty-code-figure, which is the natural root for your selectors (with one catch covered under pitfalls). - The theme's background and text color land as an inline style on
pre. That comes fromkeepBackground, which defaults totrue. tabindex="0"makes theprefocusable, so keyboard users can scroll a wide block sideways.display: gridoncodecomes from thegridoption, also on by default. It lets a highlighted line's background stretch across the full scroll width.- Every line is a
span[data-line], and highlighted words aremarkelements.
Choosing a theme
The default theme is github-dark-dimmed. You can pass the name of any theme bundled with Shiki (the list is on shiki.style/themes) or a VS Code theme JSON that you load yourself.
Two questions settle most of the config. Should code blocks follow the site's light and dark mode? If not, one dark theme is the simplest setup, and I think a dark block reads fine on a light page. And should the block background come from the theme or from your own design tokens?
| Option | Default | Change it when |
|---|---|---|
theme | "github-dark-dimmed" | You want another Shiki theme, a custom JSON theme, or a light and dark pair |
keepBackground | true | Your CSS should own the block background |
grid | true | Rarely; turning it off stops highlights from spanning the scroll width |
defaultLang | none | You write fences without a language and still want them styled |
bypassInlineCode | false | You never want inline code highlighted |
tokensMap | none | You use token highlights in inline code and want short aliases |
With keepBackground: false the pre gets no inline background. On a page wrapped in prose, the pre background from Tailwind Typography (gray-800 in its default gray theme) shows through until you set your own:
figure[data-rehype-pretty-code-figure] pre {
@apply bg-zinc-950;
}Light and dark themes
For a pair, pass an object whose keys name the color modes:
const prettyCode: Options = {
theme: { light: "github-light", dark: "github-dark" },
};With a pair, token spans no longer carry a color. Each one gets two custom properties, --shiki-light and --shiki-dark, and the pre gets --shiki-light-bg and --shiki-dark-bg. Without matching CSS, every token renders in the surrounding text color.
The rehype-pretty-code docs switch between the two with a prefers-color-scheme media query. If your site sets dark mode with a class instead, as next-themes does with attribute="class" by putting dark on <html>, the switch has to key off that class:
/* Needs keepBackground: true, which provides the --shiki-*-bg variables */
[data-rehype-pretty-code-figure] [data-theme*=" "] {
background-color: var(--shiki-light-bg);
}
[data-rehype-pretty-code-figure] [data-theme*=" "] span {
color: var(--shiki-light);
}
.dark [data-rehype-pretty-code-figure] [data-theme*=" "] {
background-color: var(--shiki-dark-bg);
}
.dark [data-rehype-pretty-code-figure] [data-theme*=" "] span {
color: var(--shiki-dark);
}data-theme lists the theme names separated by a space, so [data-theme*=" "] matches only dual-theme output. The background goes on the containers and the color on the spans. The docs' CSS also gives every token span the theme background. I left that out, because opaque span backgrounds paint over the highlighted-line color.
Meta strings
Everything you configure per block goes in the meta string after the language on the opening fence:
| Meta string | Effect | Output |
|---|---|---|
{3-4} | Highlight lines 3 to 4 | data-highlighted-line |
{2}#del {3}#add | Highlight lines with an id | data-highlighted-line-id |
/useState/ or "useState" | Highlight every match | mark[data-highlighted-chars] |
/x/2-3 | Highlight only the 2nd and 3rd match | mark[data-highlighted-chars] |
/count/#v | Highlight matches with an id | data-chars-id |
showLineNumbers | Number the lines | data-line-numbers |
showLineNumbers{41} | Start counting at 41 | inline counter-set |
title="lib/format.ts" | File name above the block | figcaption[data-rehype-pretty-code-title] |
caption="..." | Caption below the block | figcaption[data-rehype-pretty-code-caption] |
You can combine them on one fence. This is the source of the last example in this section:
```ts title="lib/format-price.ts" showLineNumbers {2} /amount/Highlighting lines
A block with {3-4}:
export function readingTime(text: string, wordsPerMinute = 200) {
const words = text.trim().split(/\s+/).length;
const minutes = Math.max(1, Math.ceil(words / wordsPerMinute));
return `${minutes} min read`;
}With ids you can mark lines differently, for example as removed and added. This block uses {2}#del {3}#add:
export async function getPosts() {
const res = await fetch(API_URL, { cache: "no-store" });
const res = await fetch(API_URL, { next: { revalidate: 3600 } });
return res.json();
}The ids only add an attribute. Until you style them, both lines look like any other highlighted line. Keep the same selector prefix as your generic highlight rule and put these after it, otherwise the generic rule wins on specificity or order:
figure[data-rehype-pretty-code-figure] [data-highlighted-line-id="del"] {
@apply border-l-red-400 bg-red-400/10;
}
figure[data-rehype-pretty-code-figure] [data-highlighted-line-id="add"] {
@apply border-l-green-400 bg-green-400/10;
}For real diffs, the @shikijs/transformers package has transformerNotationDiff, which reads // [!code ++] and // [!code --] comments in the code. You pass it through the plugin's transformers option. It is a separate install.
Highlighting words
A block with /count/#v /setCount/#s:
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}If you never style [data-highlighted-chars], the browser's default yellow mark background shows up in the middle of your dark theme.
Line numbers
showLineNumbers adds data-line-numbers to the code element. The plugin does not print any numbers. You draw them with a CSS counter:
figure[data-rehype-pretty-code-figure] code[data-line-numbers] {
counter-reset: line;
}
figure[data-rehype-pretty-code-figure] code[data-line-numbers] > [data-line]::before {
counter-increment: line;
content: counter(line);
@apply mr-4 inline-block w-4 text-right text-gray-500;
}With showLineNumbers{41} the plugin also writes counter-set: line 40 as an inline style on code, so the first line shows 41. Because the numbers are generated content, they stay out of the clipboard when someone copies the code.
export const metadata = {
title: "Blog",
description: "Notes on React, Next.js and web performance",
};Titles and captions
title adds a figcaption with data-rehype-pretty-code-title before the pre, and caption adds one with data-rehype-pretty-code-caption after it. Both carry data-language and data-theme, so you can style titles per language or print the language with content: attr(data-language).
Inside prose, a figcaption picks up the typography plugin's caption styles, which are meant for image captions. A title that should look like a file tab needs its own rules:
[data-rehype-pretty-code-title] {
@apply mt-0 rounded-t-md bg-zinc-800 px-4 py-2 font-mono text-xs text-zinc-300;
}
[data-rehype-pretty-code-title] + pre {
@apply mt-0 rounded-t-none;
}Here is the combined fence from the start of this section:
export function formatPrice(amount: number, currency = "PLN") {
return new Intl.NumberFormat("pl-PL", { style: "currency", currency }).format(amount);
}Inline code
Inline code is highlighted when it ends with a language in braces after a colon. In the Markdown source:
The result of `[1, 2, 3].join("-"){:js}` is `"1-2-3"{:js}`.Rendered: the result of [1, 2, 3].join("-") is "1-2-3".
If the suffix starts with a dot, the plugin colors the text by a theme scope instead of a language, for example .entity.name.function for a function name. tokensMap lets you define short aliases for long scope names.
Token highlights depend on the theme. With rehype-pretty-code 0.14.6 and github-dark, the .entity.name.function scope comes back as color: inherit, while .entity.name gets a color. one-dark-pro colors both. When a token highlight renders in the plain text color, check whether your theme defines that scope.
You also can't write the bare suffix as inline code. A backtick span that contains only the suffix renders as an empty element, because the plugin reads it as an empty snippet in that language. When you write about the syntax, as this post does, put it in a fenced block. bypassInlineCode: true turns inline highlighting off completely.
Styling with Tailwind and data attributes
You can't put Tailwind classes on markup the plugin generates, so the styles go in a CSS file with attribute selectors. This blog keeps them in styles/mdx.css, which only the post page imports. Plain CSS properties work fine there. The examples in this post use @apply so they can borrow Tailwind's values. A minimal set of rules for lines and highlights:
@reference "tailwindcss";
figure[data-rehype-pretty-code-figure] pre {
@apply px-0;
}
figure[data-rehype-pretty-code-figure] [data-line] {
@apply border-l-2 border-l-transparent px-3;
}
figure[data-rehype-pretty-code-figure] [data-highlighted-line] {
@apply border-l-blue-400 bg-blue-400/10;
}
[data-rehype-pretty-code-figure] [data-highlighted-chars] {
@apply rounded bg-zinc-600/50;
}The pre loses its horizontal padding because each line carries its own. That way the background and left border of a highlighted line reach the edges of the block.
The @reference line lets a standalone stylesheet use @apply without emitting Tailwind's CSS a second time. Referencing "tailwindcss" only gives you the default theme. Tailwind's docs say to reference your main stylesheet instead once you customize things like @theme, @custom-variant or @plugin. This site defines a class-based dark variant in globals.css, so an @apply dark:... in mdx.css only follows that class with @reference "./globals.css".
For a single rule you can also target the attributes from the article element with an arbitrary variant such as [&_[data-highlighted-line]]:bg-blue-400/10. I keep anything bigger than that in the CSS file, where it is easier to read.
Pitfalls
Block selectors also match inline code
Highlighted inline code is wrapped in a span that carries the same data-rehype-pretty-code-figure attribute as the block figure, and its content is a span[data-line]. A rule like [data-rehype-pretty-code-figure] [data-line] therefore gives inline snippets the line padding and border meant for blocks. That is why most rules above start with figure[data-rehype-pretty-code-figure]. Use span[data-rehype-pretty-code-figure] for rules that should only touch inline code.
Fences without a language skip the plugin
A fence with no language comes out as a bare pre and code, with no figure, no theme and no data attributes, so none of your styles apply. defaultLang fixes that. Pass it as an object with only block:
const prettyCode: Options = {
defaultLang: { block: "plaintext" },
};The string form, defaultLang: "plaintext", also applies to inline code, so every plain backtick span on the site gets the plugin's inline markup and theme colors. A language name Shiki doesn't know does not break the build; the block renders as plain text with the theme applied.
prose adds backticks around inline code
Tailwind Typography inserts a literal backtick before and after every inline code element with ::before and ::after, and that includes highlighted inline snippets. To remove them, add element modifiers on the article. In Tailwind v4 the typography README puts the element modifier first and the other modifier last:
<article className="prose dark:prose-invert prose-code:before:content-none prose-code:after:content-none">Line numbers outgrow a fixed width
The counter rule above gives the numbers a fixed w-4 box, sized for one digit. From line 10 onward the numbers are wider than the box and push into the margin. The plugin adds data-line-numbers-max-digits to code so you can widen the box per block. Give these rules the same figure prefix as the counter rule and put them after it, or the counter rule's w-4 wins on specificity:
figure[data-rehype-pretty-code-figure] code[data-line-numbers-max-digits="2"] > [data-line]::before {
@apply w-6;
}
figure[data-rehype-pretty-code-figure] code[data-line-numbers-max-digits="3"] > [data-line]::before {
@apply w-8;
}