Skip to content

Commit 412fe10

Browse files
committedJun 17, 2024··
feat(core): warning on too many instances, close #693
1 parent 0c89157 commit 412fe10

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed
 

‎docs/guide/install.md

+6
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,12 @@ const code = highlighter.codeToHtml('const a = 1', {
102102
})
103103
```
104104

105+
:::info Important Note
106+
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.
107+
108+
If running on Node.js, we recommend using the [Shorthands](#shorthands) which manages the highlighter instance and dynamic theme/language loading for you.
109+
:::
110+
105111
Additionally, if you want to load themes and languages after the highlighter is created, you can use the `loadTheme` and `loadLanguage` methods.
106112

107113
```ts twoslash

‎packages/core/src/internal.ts

+6
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,16 @@ export function setDefaultWasmLoader(_loader: LoadWasmOptions) {
1616
_defaultWasmLoader = _loader
1717
}
1818

19+
let instancesCount = 0
20+
1921
/**
2022
* Get the minimal shiki context for rendering.
2123
*/
2224
export async function getShikiInternal(options: HighlighterCoreOptions = {}): Promise<ShikiInternal> {
25+
instancesCount += 1
26+
if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)
27+
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.`)
28+
2329
async function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T> {
2430
return Promise.resolve(typeof p === 'function' ? (p as any)() : p).then(r => r.default || r)
2531
}

‎packages/core/src/types/options.ts

+5
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ export interface HighlighterCoreOptions {
2424
* Load wasm file from a custom path or using a custom function.
2525
*/
2626
loadWasm?: LoadWasmOptions
27+
/**
28+
* Emit console warnings to alert users of potential issues.
29+
* @default true
30+
*/
31+
warnings?: boolean
2732
}
2833

2934
export interface BundledHighlighterOptions<L extends string, T extends string> {

0 commit comments

Comments
 (0)
Please sign in to comment.