Skip to content

Commit

Permalink
Shiki perf (#197)
Browse files Browse the repository at this point in the history
* shiki cache + no explanation

* Remove dev optimization

With includeExplanation fix gain become negligible

* Add  doc

* fix codestyle
  • Loading branch information
ChcJohnie authored Aug 8, 2023
1 parent c5d3758 commit 8598662
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/docs/lib/shiki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,44 @@ const theme: Theme = "github-dark";
const defaultlangs: Lang[] = ["html", "tsx"];
const bg: React.CSSProperties["backgroundColor"] = "#011627";

const highlighterCache = new Map<string, Promise<Highlighter>>();

/**
* Get a shiki highlighter instance.
* Cached by theme and languages.
*/
export async function getHighlighter({
langs = defaultlangs,
}: {
langs?: Lang[];
} = {}) {
/** Preload NO languages in development */
const isDevelopment = process.env.NODE_ENV === "development";
} = {}): Promise<Highlighter> {
const key = [theme, ...langs].join("-");

const highlighter = highlighterCache.get(key);
if (highlighter) return await highlighter;

/* ✅ Create a highlighter instance with a theme */
return await getHighlighterFromShiki({
const highlighterPromise = getHighlighterFromShiki({
theme,
langs: isDevelopment ? [] : langs,
langs,
});
highlighterCache.set(key, highlighterPromise);
return await highlighterPromise;
}

/**
* Highlight code string with provided shiki highlighter.
* includeExplanation turned off to increase performance.
*/
export async function highlight(
highlighter: Highlighter,
code: string,
lang: Lang = "tsx"
) {
/** Request NO languages in development */
const isDevelopment = process.env.NODE_ENV === "development";

/* ✅ Highlight your code using the right syntax */
const tokens = highlighter.codeToThemedTokens(
code,
isDevelopment ? "" : lang,
theme
);
const tokens = highlighter.codeToThemedTokens(code, lang, theme, {
includeExplanation: false,
});
/* ⚠️ Optional: Custom rendering of code blocks */
return renderToHtml(tokens, {
bg,
Expand Down

1 comment on commit 8598662

@vercel
Copy link

@vercel vercel bot commented on 8598662 Aug 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.