Word Highlight

How to highlight specific words in code blocks using Shiki.

ShikiMarkdownMDX

Preview

Highlighted Word in Shiki
const code = `console.log('hello')`;
const highlighter = await highlight();
const html = highlighter.codeToHtml(code, {
  lang: "javascript",
  theme: "one-light",
});
Output HTML
<pre>
  <span class="shiki-highlighted-word">
    <span style="color:#4078F2;--shiki-dark:#61AFEF">highlight</span>
    <span style="color:#383A42;--shiki-dark:#ABB2BF">()</span>
  </span>
</pre>

Installation

  1. Install the following dependencies:
Shiki Transformers
pnpm i @shikijs/transformers -D
  1. Customize the styles in your CSS file if needed:
shikiShiki Highlighter#styles

The main highlighter utility to render syntax highlighted code.

Usage

shikijs/rehype

  1. Set up transformerMetaWordHighlight:
Shiki Word Highlight Transformer
import { transformerMetaWordHighlight } from "@shikijs/transformers";

const rehypeShikiOptions: RehypeShikiCoreOptions = {
  //...
  transformers: [
    transformerMetaWordHighlight({
      className: "shiki-word-highlight",
    }),
  ],
};

export { rehypeShikiOptions };
  1. Add /text-to-highlight/ to the meta string of the code block. For example:
.mdx
```js /hello/
console.log("hello world");
```