Line Numbers

How to enable line numbers in code blocks using Shiki.

ShikiMarkdownMDX

Preview

.ts
const code = `function greet() {
  console.log("Hello, World!");
}`;
const highlighter = await highlight();
const html = highlighter.codeToHtml(code, {
  lang: "javascript",
  theme: "one-light",
});

Installation

shadcn/ui

shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/shiki-show-line-numbers.json

Manual

  1. Copy the showLineNumbers transformer into your project:
.ts
import type { ShikiTransformer } from "shiki";

const showLineNumbers = (): ShikiTransformer => {
  return {
    name: "AddLineNumbers",
    pre(node) {
      const rawMeta = this.options.meta?.__raw;
      const addLineNumbers = rawMeta?.includes("lineNumbers") || false;
      const shikiStyles = node.properties.class;
      if (addLineNumbers) {
        node.properties.class = `${shikiStyles} shiki-line-numbers`;
      }
    },
  };
};

export { showLineNumbers };
  1. Import the transformer in your rehypeShiki plugin:
Rehype Shiki Options
import { showLineNumbers } from "@/utils/shiki/transformers/show-line-numbers";

const rehypeShikiOptions: RehypeShikiCoreOptions = {
  //...
  transformers: [showLineNumbers()],
};

export { rehypeShikiOptions };
  1. Customize the styles in your CSS file if needed:
shikiShiki Highlighter#styles

The main highlighter utility to render syntax highlighted code.

Usage

To enable line numbers in your code blocks, add the lineNumbers property to the code block in your MDX files:

MDX Code Block with Line Numbers
```ts lineNumbers
// Your TypeScript code here
```