Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌈

Migrating Zenn's Syntax Highlighter from Prism.js to Shiki

に公開
Inside Zennの記事です

As mentioned in the title, we have migrated Zenn's syntax highlighter from Prism.js to Shiki.

A syntax highlighter is a library that adds color to grammar, variables, and other elements based on the language of the code block when you write one in a Zenn article. For example, if you specify a language in a code block as shown below, it will apply coloring based on that language's grammar.

```js
console.log("Hello world");
```

↓ Apply highlighting

console.log("Hello world");

We had been considering a migration to Shiki for some time, but we held off to weigh the time cost of the migration against the potential benefits. Additionally, we were monitoring Prism.js v2 which is currently under development.

https://github.com/zenn-dev/zenn-community/issues/593

However, recently we received a request from @mizchi on X for syntax definitions for the Moonbit language, followed by several other voices asking for support for various other languages. Consequently, we increased the priority and began considering the migration to Shiki.

https://x.com/mizchi/status/2000544806716793084

Comparison between Prism.js and Shiki

First, we reviewed the characteristics and architectural differences of both.

Prism.js

  • Claims to be lightweight and fast.
  • Small package size (2kb for core, 300~500 bytes per language definition).
  • Proprietary language definitions. Written in JavaScript and parses tokens using regular expressions.
  • Extensive plugins.
  • Primarily for CSR (can also be used with SSR).
  • Uses CSS classes (allowing for theme switching via CSS).
  • Has unsupported patterns in edge cases for grammar parsing.

Shiki

  • Uses TextMate Grammar for language definitions.
  • Strict grammar parsing using Oniguruma (a regular expression engine).
  • Builds HTML based on HAST (easy to customize).
  • Primarily for SSR (can also be used with CSR).
  • ESModules, usable in any environment.
  • Does not use CSS classes (specifies color in the style attribute).

Summarizing my understanding of the differences:

  • Prism.js is intended for CSR and prioritizes bundle size and speed over strictness.
  • Shiki is intended for SSR and prioritizes strictness. To achieve this, it uses TextMate Grammar (a language definition format originating from the TextMate editor). TextMate Grammar relies on advanced features of the Oniguruma regular expression engine. This rich expressiveness allows for more precise language parsing.

Incidentally, Oniguruma ended development as of April 2025. A quick search reveals that many other libraries besides TextMate Grammar use Oniguruma, so the impact is likely significant. I am curious about future developments.

Benchmarks

We ran a simple benchmark test in our local environment using zenn-markdown-html.

Test Case Prism (0.2.11) Shiki (LOCAL) Difference
No code block 0.56 ms 0.57 ms ≈Same
1 code block (JavaScript) 0.46 ms 1.98 ms 4.3x slower
5 code blocks (different languages) 0.68 ms 1.67 ms 2.5x slower
diff mode 0.48 ms 0.72 ms 1.5x slower
Large code block (50 lines) 0.87 ms 4.53 ms 5.2x slower

Although Prism.js has a speed advantage, Shiki is still sufficiently fast as the difference is at the millisecond level.

Benchmark script
/**
 * zenn-markdown-html benchmark
 *
 * Usage:
 *   # Test release version (package.json version)
 *   pnpm bench
 *
 *   # Test local version
 *   pnpm bench:local
 *
 * Version change:
 *   Change zenn-markdown-html version in package.json and pnpm install
 */

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const isLocal = process.argv.includes('--local');

// Dynamically import local or installed version
// Both are CommonJS so use require
const modulePath = isLocal ? '../../lib/index.js' : 'zenn-markdown-html';
const mod = require(modulePath);
const markdownToHtml = mod.default || mod;

console.log(`\n📦 Testing: ${isLocal ? 'LOCAL' : 'npm'} version\n`);
console.log('='.repeat(60));

// ------------------------------------------------------------
// Test cases
// ------------------------------------------------------------

const testCases = {
  'No code block': `
# Title

This is a paragraph. It has **bold** and *italic* text.

- List 1
- List 2
- List 3

\> Quote
`.trim(),

  '1 code block (JavaScript)': `
# Title

\`\`\`javascript
console.log('hello');
const x = 1;
const y = 2;
\`\`\`
`.trim(),

  '5 code blocks (different languages)': `
# Article Title

## JavaScript

\`\`\`javascript
console.log('hello');
\`\`\`

## TypeScript

\`\`\`typescript
const x: number = 1;
interface User { name: string; }
\`\`\`

## Python

\`\`\`python
def hello():
    print("hello")
\`\`\`

## HTML

\`\`\`html
<div class="container">
  <p>Hello</p>
</div>
\`\`\`

## CSS

\`\`\`css
.container {
  display: flex;
  justify-content: center;
}
\`\`\`
`.trim(),

  'diff mode': `
# Changes

\`\`\`javascript diff
-const old = 1;
+const new = 2;
 const unchanged = 3;
-removed();
+added();
\`\`\`
`.trim(),

  'Large code block (50 lines)': `
# Large Code

\`\`\`javascript
${Array.from({ length: 50 }, (_, i) => `const line${i} = ${i};`).join('\n')}
\`\`\`
`.trim(),
};

// ------------------------------------------------------------
// Run benchmark
// ------------------------------------------------------------

async function runBenchmark(name, markdown, iterations = 10) {
  // Warm up
  await markdownToHtml(markdown);

  const times = [];

  for (let i = 0; i < iterations; i++) {
    const start = performance.now();
    await markdownToHtml(markdown);
    const end = performance.now();
    times.push(end - start);
  }

  const avg = times.reduce((a, b) => a + b, 0) / times.length;
  const min = Math.min(...times);
  const max = Math.max(...times);

  console.log(`\n📝 ${name}`);
  console.log(`   Average: ${avg.toFixed(2)} ms`);
  console.log(`   Min: ${min.toFixed(2)} ms`);
  console.log(`   Max: ${max.toFixed(2)} ms`);

  return { name, avg, min, max };
}

// Main execution
const results = [];

for (const [name, markdown] of Object.entries(testCases)) {
  const result = await runBenchmark(name, markdown);
  results.push(result);
}

// Summary
console.log('\n' + '='.repeat(60));
console.log('📊 Summary (Average time)');
console.log('='.repeat(60));

for (const r of results) {
  const bar = '█'.repeat(Math.ceil(r.avg / 5));
  console.log(`${r.name.padEnd(35)} ${r.avg.toFixed(2).padStart(8)} ms ${bar}`);
}

console.log('\n');

Implementation Migration

Here is the Pull Request for this change (though there were several subsequent PRs for bug fixes):

https://github.com/zenn-dev/zenn-editor/pull/611

We originally had a custom implementation for diff highlighting, and while porting that involved a significant amount of changes, the actual transition from Prism.js to Shiki was not very difficult. (Of course, we had a lot of help from AI Coding.)

Syntax highlighting is performed as part of the process of converting Markdown to HTML. We use a library called markdown-it for conversion, and the implementation is such that Shiki is inserted as a plugin for it.

I will explain a few points of ingenuity in the implementation.

Lazy Loading

The Shiki instance is created using the singleton pattern. By initializing it with no languages loaded, we minimize the load time.

  // Initialize with an empty set of languages (fast)
  highlighterInstance = await createHighlighter({
    themes: [SHIKI_THEME],
    langs: [],
  });

Just before the highlighting process, we check if the target language is loaded and load it if it isn't.

/**
 * Checks if the language is supported and loads it if necessary
 */
async function ensureLanguageLoaded(
  highlighter: Highlighter,
  langName: string
): Promise<boolean> {
  // Check if already loaded
  const loadedLangs = highlighter.getLoadedLanguages();
  if (loadedLangs.includes(langName)) {
    return true;
  }

  // Check if included in bundledLanguages
  if (langName in bundledLanguages) {
    await highlighter.loadLanguage(langName as BundledLanguage);
    return true;
  }

  return false;
}

Asynchronous Processing

Shiki's highlighting process includes asynchronous functions. If there are multiple code blocks in the Markdown, asynchronous processing should have better performance than synchronous processing, so we perform syntax highlighting in bulk using asynchronous processing.

Specifically, we perform the following process:

  1. When markdown-it detects a code block, it saves the code block information as temporary data in an array and inserts a placeholder <!--SHIKI_CODE_BLOCK_xxxxxxxx--> into the HTML.
  2. All temporarily saved code blocks are processed for highlighting using Promise.all.
  3. The placeholders are replaced with the highlighted HTML.

Transformer

A feature called Transformers was useful.

Shiki uses HAST (HTML AST) in the process of generating highlighted HTML. By manipulating HAST, we can customize the generated HTML. In the case of Prism.js, we were performing string matching against the generated HTML to add HTML tags or attributes for customization; using Transformers allowed us to implement this more reliably.

Migration

At Zenn, we save the HTML converted from Markdown in the database. Since the HTML is already highlighted with Prism.js, we need to reconvert it using Shiki. However, since there are a vast number of articles, the conversion takes time, meaning both Prism.js and Shiki coexist during this period.

Fortunately, there were no conflicts between the CSS used for the HTML generated by Prism.js and the styles generated by Shiki, so the coexistence was not an issue. We decided to take our time to reconvert existing articles.

Performance Verification

Currently, the Markdown-to-HTML conversion process (zenn-markdown-html) operates as an HTTP service on Cloud Run Functions (1st generation). We converted it to the Shiki version and performed performance verification.

These are the metrics when processing 10,000 items at 20 requests/second for both.

Prism.js version
Memory usage is around 120MB, and it is handling 20 requests/second stably.

Shiki version
Memory usage is nearing 512MB (the maximum setting), and it is only handling about 10 requests/second. The execution time is also clearly longer.

Although there is a possibility of implementation issues, we did not pursue it deeply for now. Upon adjusting the memory, we found that with 2GB, the performance in terms of execution time is comparable to Prism.js. Since the CPU granted to Cloud Functions increases according to the maximum memory amount, it is possible that the performance simply improved.

As another comparative verification, we compared Cloud Run Functions 1st generation and 2nd generation. The 1st generation processes one request per instance simultaneously. To increase parallelism, it launches many instances. The 2nd generation processes multiple requests per instance. We thought the Shiki version, which used the singleton pattern and lazy loading, might have performance benefits in the 2nd generation.

As before, these are metrics when processing 10,000 items at 20 requests/second. Memory is set to 2GB.

Shiki version (1st generation)

Shiki version (2nd generation)
The number of concurrent connections is set to 20. (*The 2nd generation is a Cloud Run environment, so the metrics obtained differ from the 1st generation.)

For the 2nd generation, we tried several times with different numbers of concurrent connections, but in all cases, the 1st generation resulted in a lower execution time (latency) per request. This result differed from our expectations. We would like to take more time to verify this.

See you next time!

GitHubで編集を提案
Zenn Tech Blog
Zenn Tech Blog

Discussion