Synchronous Usage | Shiki

ID: 1739https://shiki.matsu.io/guide/sync-usage
Source

Synchronous Usage

The await createHighlighter() and highlighter.codeToHtml() already separate the asynchronous and synchronous parts of Shiki. For most cases you can resolve the async part during the initialization phase and then use the highlighter synchronously.

In some extreme cases where you need to run Shiki completely synchronously, since v1.16 we provide a synchronous version of the core API. You can use createHighlighterCoreSync to create a highlighter instance synchronously.

import js from '@shikijs/langs/javascript'
import nord from '@shikijs/themes/nord'
import { createHighlighterCoreSync } from 'shiki/core'
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'

const shiki = createHighlighterCoreSync({
  themes: [nord],
  langs: [js],
  engine: createJavaScriptRegexEngine()
})

const html = shiki.highlight('console.log(1)', {
  lang: 'js',
  theme: 'nord'
})

When doing so, it requires all themes and langs to be provided as plain objects. An explicit engine is also required. With the new JavaScript RegExp engine you can create an engine instance synchronously as well.

The Oniguruma Engine can only be created asynchronously, so you must resolve the engine promise before creating the sync highlighter.

import js from '@shikijs/langs/javascript'
import nord from '@shikijs/themes/nord'
import { createHighlighterCoreSync } from 'shiki/core'
import { createOnigurumaEngine } from 'shiki/engine/oniguruma'

// Load this somewhere beforehand
const engine = await createOnigurumaEngine(import('shiki/wasm'))

const shiki = createHighlighterCoreSync({
  themes: [nord],
  langs: [js],
  engine, // if a resolved engine is passed in, the rest can still be synced.
})

const html = shiki.highlight('console.log(1)', {
  lang: 'js',
  theme: 'nord'
})