Skip to content

Commit

Permalink
feat(core): warning on too many instances, close #693
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jun 17, 2024
1 parent 0c89157 commit 412fe10
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/guide/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ const code = highlighter.codeToHtml('const a = 1', {
})
```

:::info Important Note
Highlighter instance should be **long-lived singleton**. You might need to cache it somewhere and reuse it across your application. Avoid calling `getHighlighter` in hot functions or loops.

If running on Node.js, we recommend using the [Shorthands](#shorthands) which manages the highlighter instance and dynamic theme/language loading for you.
:::

Additionally, if you want to load themes and languages after the highlighter is created, you can use the `loadTheme` and `loadLanguage` methods.

```ts twoslash
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@ export function setDefaultWasmLoader(_loader: LoadWasmOptions) {
_defaultWasmLoader = _loader
}

let instancesCount = 0

/**
* Get the minimal shiki context for rendering.
*/
export async function getShikiInternal(options: HighlighterCoreOptions = {}): Promise<ShikiInternal> {
instancesCount += 1
if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)
console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance.`)

async function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T> {
return Promise.resolve(typeof p === 'function' ? (p as any)() : p).then(r => r.default || r)
}
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export interface HighlighterCoreOptions {
* Load wasm file from a custom path or using a custom function.
*/
loadWasm?: LoadWasmOptions
/**
* Emit console warnings to alert users of potential issues.
* @default true
*/
warnings?: boolean
}

export interface BundledHighlighterOptions<L extends string, T extends string> {
Expand Down

0 comments on commit 412fe10

Please sign in to comment.