Build-Time Syntax Highlighting With Shiki and Rehype
Use Shiki and rehype to highlight Markdown, HTML, and inline code at build time without shipping a syntax-highlighting library to the browser.
When writing code blocks by hand, the browser provides a monospace font and preserves line breaks, but it lacks the ability to differentiate between keywords, strings, comments, and variables. This can make reading blocks of code, such as TypeScript, challenging. However, utilizing ShikiJS and Rehype can enhance readability without the need to ship a highlighting library to the reader's browser.
ShikiJS leverages VS Code's TextMate grammars and themes, allowing the code on the page to resemble the code in an editor. This highlighting can occur during the page's build process or in the browser, depending on preference. The Rehype plugin serves as the intermediary between Markdown conversion and stringification, enabling the integration of ShikiJS.
For Markdown-based posts, the plugin connects between Markdown-to-HTML conversion and stringification. Conversely, if posts are directly in HTML, the plugin operates on the syntax tree, parsing the HTML with rehype-parse and passing the resulting tree to ShikiJS.
Identifying the code elements involves looking for elements with a specific class, which is precisely what the Rehype plugin generates. The plugin searches for a code element with a class and relies on the remark-rehype plugin to produce this.
With ShikiJS, you can customize themes for light and dark modes, with the pair version emitting CSS variables for easy toggling. Importing only the required languages can also help reduce bundle size. The postprocess transformer hook does not run in this scenario, as the plugin works on the syntax tree rather than HTML strings.
Inline code presents its own challenge, as default highlighting leaves it grayed out. However, by enabling the tailing curly colon syntax in ShikiJS, you can highlight inline code by appending a language marker to the end of the snippet. This marker is then stripped from the output, leaving the code readable yet highlighted.
Written by urgent.news from HackerNoon's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.