Skip to content

Commit

Permalink
perf(mdx): cache highlighter
Browse files Browse the repository at this point in the history
  • Loading branch information
tszhong0411 committed Aug 18, 2024
1 parent b44663d commit fc9de7c
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/mdx/src/core/plugins/rehype/rehype-inline-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import type { RehypeShikiCoreOptions } from '@shikijs/rehype/core'
import type { Root } from 'hast'
import { bundledLanguages, getSingletonHighlighter } from 'shiki'
import { bundledLanguages, getSingletonHighlighter, type Highlighter } from 'shiki'
import type { Plugin } from 'unified'
import { visit } from 'unist-util-visit'

Expand All @@ -16,12 +16,22 @@ const inlineShikiRegex = /(.*){:(.*)}$/
const themeNames = Object.values(DEFAULT_SHIKI_THEMES)
const themeKeys = Object.keys(DEFAULT_SHIKI_THEMES)

let cachedHighlighter: Highlighter | null = null

const getHighlighter = async () => {
if (cachedHighlighter) return cachedHighlighter

cachedHighlighter = await getSingletonHighlighter({
themes: themeNames,
langs: Object.keys(bundledLanguages)
})

return cachedHighlighter
}

export const rehypeInlineCode: Plugin<[RehypeShikiCoreOptions], Root> = () => {
return async (tree) => {
const highlighter = await getSingletonHighlighter({
themes: themeNames,
langs: Object.keys(bundledLanguages)
})
const highlighter = await getHighlighter()

visit(tree, 'element', (node, index, parent) => {
if (node.tagName !== 'code') return
Expand Down

0 comments on commit fc9de7c

Please sign in to comment.