### Load all bundled themes and languages into highlighter Source: https://shiki.style/guide/install Provides an example of loading all available themes and languages bundled with Shiki into the highlighter instance. This is generally not recommended for performance reasons but can be useful for specific use cases or testing. ```typescript import { bundledLanguages, bundledThemes, createHighlighter } from 'shiki' const highlighter = await createHighlighter({ themes: Object.keys(bundledThemes), langs: Object.keys(bundledLanguages), }) highlighter.codeToHtml('const a = 1', { lang: 'javascript', theme: 'poimandres' }) ``` -------------------------------- ### Synchronous highlighting with explicitly loaded language Source: https://shiki.style/guide/install Shows an example where `createHighlighter` is used with specific themes and languages. If an attempt is made to highlight code in a language not explicitly loaded, an error is thrown. The example demonstrates loading the missing language (`javascript`) to resolve the issue. ```typescript import { createHighlighter } from 'shiki' const highlighter = await createHighlighter({ themes: ['slack-dark'], langs: ['css'] }) highlighter.codeToHtml( 'const a = 1', { lang: 'javascript', theme: 'slack-dark' } ) Throw error, `javascript` is not loaded await highlighter.loadLanguage('javascript') // load the language // now it works ``` -------------------------------- ### Install Shiki via npm, yarn, pnpm, bun, or deno Source: https://shiki.style/guide/install Demonstrates the installation commands for Shiki using different package managers like npm, yarn, pnpm, bun, and deno. These commands add Shiki as a development dependency. ```bash npm install -D shiki ``` ```bash yarn add -D shiki ``` ```bash pnpm add -D shiki ``` ```bash bun add -D shiki ``` ```bash deno add npm:shiki ``` -------------------------------- ### Install @shikijs/markdown-it Source: https://shiki.style/packages/markdown-it Commands to install the Shiki markdown-it plugin using various package managers. ```bash npm i -D @shikijs/markdown-it ``` ```bash yarn add -D @shikijs/markdown-it ``` ```bash pnpm add -D @shikijs/markdown-it ``` ```bash bun add -D @shikijs/markdown-it ``` ```bash deno add npm:@shikijs/markdown-it ``` -------------------------------- ### Initialize Shiki Highlighter in Node.js Source: https://shiki.style/guide/install Demonstrates how to initialize the Shiki highlighter using both standard ESM import syntax and dynamic imports for CommonJS environments. ```typescript // ESM import { createHighlighter } from 'shiki' async function main() { const highlighter = await createHighlighter({ themes: ['vitesse-dark'], langs: ['javascript'], }) const code = highlighter.codeToHtml('const a = 1', { theme: 'vitesse-dark', lang: 'javascript', }) } ``` ```typescript // CJS async function main() { const { createHighlighter } = await import('shiki') const highlighter = await createHighlighter({ themes: ['vitesse-dark'], langs: ['javascript'], }) const code = highlighter.codeToHtml('const a = 1', { theme: 'vitesse-dark', lang: 'javascript' }) } ``` -------------------------------- ### Install @shikijs/colorized-brackets Source: https://shiki.style/packages/colorized-brackets Commands to install the package using various package managers. ```bash npm i -D @shikijs/colorized-brackets ``` ```bash yarn add -D @shikijs/colorized-brackets ``` ```bash pnpm add -D @shikijs/colorized-brackets ``` ```bash bun add -D @shikijs/colorized-brackets ``` ```bash deno add npm:@shikijs/colorized-brackets ``` -------------------------------- ### Install @shikijs/transformers Source: https://shiki.style/packages/transformers Installation commands for various package managers to add the transformers library as a development dependency. ```bash npm i -D @shikijs/transformers ``` ```bash yarn add -D @shikijs/transformers ``` ```bash pnpm add -D @shikijs/transformers ``` ```bash bun add -D @shikijs/transformers ``` ```bash deno add npm:@shikijs/transformers ``` -------------------------------- ### Create a synchronous highlighter instance with Shiki Source: https://shiki.style/guide/install Illustrates creating a highlighter instance using `createHighlighter`. This instance can then be used to synchronously convert code to HTML. It's recommended to explicitly list themes and languages for better performance and to cache the highlighter instance. ```typescript import { createHighlighter } from 'shiki' // `createHighlighter` is async, it initializes the internal and // loads the themes and languages specified. const highlighter = await createHighlighter({ themes: ['nord'], langs: ['javascript'], }) // then later you can use `highlighter.codeToHtml` synchronously // with the loaded themes and languages. const code = highlighter.codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' }) ``` -------------------------------- ### Initialize Oniguruma Engine Source: https://shiki.style/guide/regex-engines Shows the setup for the default Oniguruma engine, which requires loading the WebAssembly module. ```typescript import { createHighlighter } from 'shiki' import { createOnigurumaEngine } from 'shiki/engine/oniguruma' const shiki = await createHighlighter({ themes: ['nord'], langs: ['javascript'], engine: createOnigurumaEngine(import('shiki/wasm')) }) ``` -------------------------------- ### Install @shikijs/twoslash Source: https://shiki.style/packages/twoslash Installation commands for the @shikijs/twoslash package using various popular JavaScript package managers. ```bash npm install -D @shikijs/twoslash ``` ```bash yarn add -D @shikijs/twoslash ``` ```bash pnpm add -D @shikijs/twoslash ``` ```bash bun add -D @shikijs/twoslash ``` ```bash deno add npm:@shikijs/twoslash ``` -------------------------------- ### Install @shikijs/rehype package Source: https://shiki.style/packages/rehype Commands to install the @shikijs/rehype plugin using various package managers. ```bash npm i -D @shikijs/rehype yarn add -D @shikijs/rehype pnpm add -D @shikijs/rehype bun add -D @shikijs/rehype deno add npm:@shikijs/rehype ``` -------------------------------- ### Implement Shiki via CDN in Browser Source: https://shiki.style/guide/install Shows how to load Shiki directly in the browser using ESM modules from a CDN provider like esm.sh to highlight code snippets dynamically. ```html
``` -------------------------------- ### Get code tokens using Shiki's codeToTokens Source: https://shiki.style/guide/install Demonstrates using `codeToTokens` to parse code into an array of tokens, which can then be used for custom rendering. This provides more control over the output compared to `codeToHtml`. It requires specifying the language and theme. ```typescript import { codeToTokens } from 'shiki' const { tokens } = await codeToTokens('
bar
', { lang: 'html', theme: 'min-dark' }) ``` -------------------------------- ### Install Shiki CLI Globally Source: https://shiki.style/packages/cli Provides commands to install the Shiki CLI globally using different package managers like npm, yarn, pnpm, and bun. Upon global installation, command aliases like `shiki` and `skat` are registered for convenience. ```sh npm i -g @shikijs/cli ``` ```sh yarn global add @shikijs/cli ``` ```sh pnpm add -g @shikijs/cli ``` ```sh bun add -g @shikijs/cli ``` ```sh deno install -gREn skat npm:@shikijs/cli ``` ```sh skat src/index.ts ``` -------------------------------- ### Synchronous Highlighter with JavaScript Engine Source: https://shiki.style/guide/sync-usage This example demonstrates how to create and use a Shiki highlighter instance synchronously using the JavaScript RegExp engine. ```APIDOC ## POST /websites/shiki_style/synchronous-js ### Description Creates and uses a Shiki highlighter instance synchronously with the JavaScript RegExp engine. This is suitable for scenarios where asynchronous operations are not desired during initialization. ### Method POST ### Endpoint /websites/shiki_style/synchronous-js ### Parameters #### Request Body - **code** (string) - Required - The code snippet to highlight. - **lang** (string) - Required - The programming language of the code snippet (e.g., 'js'). - **theme** (string) - Required - The theme to use for highlighting (e.g., 'nord'). ### Request Example ```json { "code": "console.log(1)", "lang": "js", "theme": "nord" } ``` ### Response #### Success Response (200) - **html** (string) - The highlighted HTML string of the code snippet. #### Response Example ```json { "html": "
console.log(<span class=\"token number\">1)
" } ``` ``` -------------------------------- ### Install Shiki CLI as a Project Dependency Source: https://shiki.style/packages/cli Shows the commands to install the `@shikijs/cli` package as a dependency within a project using various package managers. This is useful for integrating Shiki's functionality into project build processes or scripts. ```sh npm i @shikijs/cli ``` ```sh yarn add @shikijs/cli ``` ```sh pnpm add @shikijs/cli ``` ```sh bun add @shikijs/cli ``` ```sh deno add npm:@shikijs/cli ``` -------------------------------- ### Load themes and languages after highlighter creation Source: https://shiki.style/guide/install Demonstrates how to load additional themes and languages into an existing Shiki highlighter instance using `loadTheme` and `loadLanguage`. This is useful when you need to extend the highlighter's capabilities after its initial creation. ```typescript // load themes and languages after creation await highlighter.loadTheme('vitesse-light') await highlighter.loadLanguage('css') ``` -------------------------------- ### Install @shikijs/markdown-exit Source: https://shiki.style/packages/markdown-exit Installation commands for various package managers to add the @shikijs/markdown-exit dependency to your project. ```bash npm i -D @shikijs/markdown-exit ``` ```bash yarn add -D @shikijs/markdown-exit ``` ```bash pnpm add -D @shikijs/markdown-exit ``` ```bash bun add -D @shikijs/markdown-exit ``` ```bash deno add npm:@shikijs/markdown-exit ``` -------------------------------- ### Synchronous Highlighter with Oniguruma Engine Source: https://shiki.style/guide/sync-usage This example shows how to create a synchronous Shiki highlighter instance when using the Oniguruma engine, which requires asynchronous loading of the WASM module. ```APIDOC ## POST /websites/shiki_style/synchronous-oniguruma ### Description Creates and uses a Shiki highlighter instance synchronously after asynchronously loading the Oniguruma engine. This approach allows for synchronous highlighting while accommodating the asynchronous nature of the Oniguruma WASM module. ### Method POST ### Endpoint /websites/shiki_style/synchronous-oniguruma ### Parameters #### Request Body - **code** (string) - Required - The code snippet to highlight. - **lang** (string) - Required - The programming language of the code snippet (e.g., 'js'). - **theme** (string) - Required - The theme to use for highlighting (e.g., 'nord'). ### Request Example ```json { "code": "console.log(1)", "lang": "js", "theme": "nord" } ``` ### Response #### Success Response (200) - **html** (string) - The highlighted HTML string of the code snippet. #### Response Example ```json { "html": "
console.log(<span class=\"token number\">1)
" } ``` ``` -------------------------------- ### Install @shikijs/monaco Package Source: https://shiki.style/packages/monaco Install the @shikijs/monaco package as a development dependency using various package managers. This package enables Shiki's syntax highlighting engine for Monaco Editor. ```shell npm i -D @shikijs/monaco ``` ```shell yarn add -D @shikijs/monaco ``` ```shell pnpm add -D @shikijs/monaco ``` ```shell bun add -D @shikijs/monaco ``` ```shell deno add npm:@shikijs/monaco ``` -------------------------------- ### Convert code to HAST using Shiki's codeToHast Source: https://shiki.style/guide/install Shows how to use `codeToHast` to convert code into a Hast (Hypertext Abstract Syntax Tree) structure. This allows for fine-grained manipulation of the highlighted code's structure before rendering. It requires specifying the language and theme. ```typescript import { codeToHast } from 'shiki' const hast = await codeToHast('.text-red { color: red; }', { lang: 'css', theme: 'catppuccin-mocha' }) ``` -------------------------------- ### Advanced Configuration Options Source: https://shiki.style/packages/colorized-brackets Examples of using language-specific overrides and enabling explicit triggers for code blocks. ```typescript // Language-specific overrides const transformer = transformerColorizedBrackets({ langs: { ts: myCustomTypescriptConfig }, }) // Explicit trigger usage const transformer = transformerColorizedBrackets({ explicitTrigger: true, }) ``` -------------------------------- ### Render whitespace and indent guides Source: https://shiki.style/packages/transformers Visualizes tabs, spaces, and indentation levels as distinct spans. Requires custom CSS to render the visual markers like dots or vertical lines. ```css pre.shiki .tab::before { content: '⇥'; position: absolute; opacity: 0.3; } pre.shiki .space::before { content: '·'; position: absolute; opacity: 0.3; } ``` ```css pre.shiki .indent::before { content: ''; position: absolute; opacity: 0.15; width: 1px; height: 100%; background-color: currentColor; } ``` -------------------------------- ### Configure Twoslash Renderers Source: https://shiki.style/packages/twoslash Examples of configuring the Twoslash transformer with specific renderers like rendererRich or rendererClassic to customize the output HTML structure. ```typescript import { rendererRich, transformerTwoslash } from '@shikijs/twoslash' transformerTwoslash({ renderer: rendererRich() }) ``` ```typescript import { rendererClassic, transformerTwoslash } from '@shikijs/twoslash' transformerTwoslash({ renderer: rendererClassic() }) ``` -------------------------------- ### Install modern-monaco Package Source: https://shiki.style/packages/monaco Install the modern-monaco package as a development dependency using various package managers. This library offers a more convenient API for building Monaco Editor applications with built-in Shiki integration. ```shell npm i -D modern-monaco ``` ```shell yarn add -D modern-monaco ``` ```shell pnpm add -D modern-monaco ``` ```shell bun add -D modern-monaco ``` ```shell deno add npm:modern-monaco ``` -------------------------------- ### Vue SFC with Twoslash Highlighting Source: https://shiki.style/packages/vitepress Demonstrates how to use 'vue twoslash' syntax in markdown to enable syntax highlighting and type information for Vue Single File Components. The example shows a basic Vue component with script, template, and reactive state. ```vue ``` -------------------------------- ### Highlight code to HTML using Shiki's codeToHtml shorthand Source: https://shiki.style/guide/install Uses the `codeToHtml` function from Shiki to convert a code snippet into an HTML string with inline styles for syntax highlighting. It requires specifying the language and theme. The function is asynchronous and caches themes/languages automatically. ```typescript import { codeToHtml } from 'shiki' const code = 'const a = 1' // input code const html = await codeToHtml( code, { lang: 'javascript', theme: 'vitesse-dark' } ) console.log(html) // highlighted html string ``` -------------------------------- ### Configure Markdown Exit with Shiki Source: https://shiki.style/packages/markdown-exit Basic setup for integrating Shiki into markdown-exit. Requires using the renderAsync method due to the asynchronous nature of highlighting. ```typescript import Shiki from '@shikijs/markdown-exit' import { createMarkdownExit } from 'markdown-exit' const md = createMarkdownExit() md.use(Shiki({ themes: { light: 'vitesse-light', dark: 'vitesse-dark', } })) const html = await md.renderAsync('# Title\n```ts\nconsole.log("Hello, World!")\n```') ``` -------------------------------- ### Apply Decorations using Character Offsets Source: https://shiki.style/guide/decorations This example shows how to apply decorations using 0-indexed character offsets relative to the entire code string, instead of line and character positions. This provides an alternative way to pinpoint specific code segments for styling. The `codeToHtml` function and its `decorations` option are used. ```typescript import { codeToHtml } from 'shiki' const html = await codeToHtml(code, { theme: 'vitesse-light', lang: 'ts', decorations: [ { start: 21, end: 24, properties: { class: 'highlighted-word' } } ] }) ``` -------------------------------- ### Fine-Grained Bundle Optimization with Shiki Core and JavaScript Engine Source: https://shiki.style/guide/best-performance For web applications or resource-constrained environments, use fine-grained bundles to reduce Shiki's bundle size and memory usage. Import specific modules like `shiki/core`, `shiki/engine/javascript`, and language/theme imports instead of pre-built bundles. This example demonstrates creating a highlighter with specific themes, languages, and the JavaScript regex engine. ```typescript import { createHighlighterCore } from 'shiki/core' import { createJavaScriptRegexEngine } from 'shiki/engine/javascript' const highlighter = await createHighlighterCore({ themes: [ import('@shikijs/themes/nord'), import('@shikijs/themes/dark-plus'), // ... ], langs: [ import('@shikijs/langs/typescript'), import('@shikijs/langs/javascript'), // ... ], engine: createJavaScriptRegexEngine() }) ``` -------------------------------- ### Initialize and execute Twoslash via CDN Source: https://shiki.style/packages/twoslash Demonstrates how to set up Twoslash in a browser environment using unstorage for caching and the twoslash-cdn wrapper. It includes the initialization of the storage driver, the creation of the Twoslash instance, and the asynchronous preparation of types before rendering code to HTML. ```javascript import { createTransformerFactory, rendererRich } from 'https://esm.sh/@shikijs/twoslash@latest/core' import { codeToHtml } from 'https://esm.sh/shiki@latest' import { createTwoslashFromCDN } from 'https://esm.sh/twoslash-cdn@latest' import { createStorage } from 'https://esm.sh/unstorage@latest' import indexedDbDriver from 'https://esm.sh/unstorage@latest/drivers/indexedb' const storage = createStorage({ driver: indexedDbDriver({ base: 'twoslash-cdn' }), }) const twoslash = createTwoslashFromCDN({ storage, compilerOptions: { lib: ['esnext', 'dom'], }, }) const transformerTwoslash = createTransformerFactory(twoslash.runSync)({ renderer: rendererRich(), }) const app = document.getElementById('app') const source = ` import { ref } from 'vue' console.log("Hi! Shiki + Twoslash on CDN :)") const count = ref(0) // ^? `.trim() await twoslash.prepareTypes(source) app.innerHTML = await codeToHtml(source, { lang: 'ts', theme: 'vitesse-dark', transformers: [transformerTwoslash], }) ``` -------------------------------- ### Initialize Global Highlighter Instance Source: https://shiki.style/packages/next Demonstrates how to create a persistent highlighter instance using `createHighlighter` to share across both server and client components, optimizing performance by preloading specific languages and themes. ```ts import { createHighlighter } from 'shiki' const highlighter = createHighlighter({ themes: ['nord'], langs: ['javascript'], }) const html = (await highlighter).codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' }) ``` -------------------------------- ### Use Fine-grained Bundle Source: https://shiki.style/packages/markdown-it Optimizing bundle size by using the core package and providing a custom highlighter instance. ```typescript import { fromHighlighter } from '@shikijs/markdown-it/core' import MarkdownIt from 'markdown-it' import { createHighlighterCore } from 'shiki/core' import { createOnigurumaEngine } from 'shiki/engine/oniguruma' const highlighter = await createHighlighterCore({ themes: [ import('@shikijs/themes/vitesse-light') ], langs: [ import('@shikijs/langs/javascript'), ], engine: createOnigurumaEngine(() => import('shiki/wasm')) }) const md = MarkdownIt() md.use(fromHighlighter(highlighter, { /* options */ })) ``` -------------------------------- ### Implement Fine-grained Bundle Source: https://shiki.style/packages/markdown-exit Optimizes bundle size by using the core entry point and manually providing a pre-configured highlighter instance. ```typescript import { fromHighlighter } from '@shikijs/markdown-exit/core' import { createMarkdownExit } from 'markdown-exit' import { createHighlighterCore } from 'shiki/core' import { createOnigurumaEngine } from 'shiki/engine/oniguruma' const highlighter = await createHighlighterCore({ themes: [ import('@shikijs/themes/vitesse-light') ], langs: [ import('@shikijs/langs/javascript'), ], engine: createOnigurumaEngine(() => import('shiki/wasm')) }) const md = createMarkdownExit() md.use(fromHighlighter(highlighter, { /* options */ })) ``` -------------------------------- ### Install @shikijs/vitepress-twoslash Plugin Source: https://shiki.style/packages/vitepress Installs the VitePress plugin for Shiki Twoslash using npm, yarn, pnpm, or bun. This plugin enables TypeScript type hover functionality in VitePress markdown code snippets. ```bash npm i -D @shikijs/vitepress-twoslash ``` ```bash yarn add -D @shikijs/vitepress-twoslash ``` ```bash pnpm add -D @shikijs/vitepress-twoslash ``` ```bash bun add -D @shikijs/vitepress-twoslash ``` ```bash deno add npm:@shikijs/vitepress-twoslash ``` -------------------------------- ### Synchronous Highlighter Initialization with JavaScript Engine Source: https://shiki.style/guide/sync-usage Demonstrates how to initialize the Shiki highlighter synchronously using the JavaScript RegExp engine. This approach requires providing themes, languages, and the engine instance as plain objects. ```typescript 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' }) ``` -------------------------------- ### Run Shiki CLI to Highlight Files Source: https://shiki.style/packages/cli Demonstrates how to use the Shiki CLI to highlight local files or remote files from URLs. The CLI mimics the `cat` command's functionality but adds syntax highlighting. ```bash npx @shikijs/cli README.md ``` ```bash npx @shikijs/cli \ 'https://github.com/shikijs/shiki/blob/main/taze.config.ts?raw=true' ``` -------------------------------- ### Use Shiki Web Bundle for Common Web Languages Source: https://shiki.style/guide/bundles Demonstrates how to use the `shiki/bundle/web` preset, which includes common web languages and frameworks. This bundle is suitable for web applications and offers a balance between features and bundle size. It imports necessary components like `createHighlighter` and specifies languages and themes for code highlighting. ```typescript import { BundledLanguage, BundledTheme, codeToHtml, createHighlighter } from 'shiki/bundle/web' const highlighter = await createHighlighter({ langs: ['html', 'css', 'js'], themes: ['github-dark', 'github-light'], }) ``` -------------------------------- ### Configure Custom Shiki Engine Source: https://shiki.style/guide/regex-engines Demonstrates how to inject a custom engine implementation into the Shiki highlighter initialization process. ```typescript import { createHighlighter } from 'shiki' const shiki = await createHighlighter({ themes: ['nord'], langs: ['javascript'], engine: { /* custom engine */ } }) ``` -------------------------------- ### Use Pre-compiled Languages with Raw Engine Source: https://shiki.style/guide/regex-engines Shows how to use pre-compiled languages and the raw engine to skip transpilation and reduce startup time. ```typescript import { createHighlighterCore } from 'shiki/core' import { createJavaScriptRawEngine } from 'shiki/engine/javascript' const highlighter = await createHighlighterCore({ langs: [ import('@shikijs/langs/javascript'), import('@shikijs/langs/typescript'), import('@shikijs/langs-precompiled/javascript'), import('@shikijs/langs-precompiled/typescript'), ], themes: [ import('@shikijs/themes/nord'), ], engine: createJavaScriptRegexEngine(), engine: createJavaScriptRawEngine(), }) ``` -------------------------------- ### Configure Shiki for Cloudflare Workers Source: https://shiki.style/guide/install Provides a pattern for using Shiki in Cloudflare Workers by utilizing the core highlighter and manually loading the Oniguruma WASM asset. ```typescript import js from '@shikijs/langs/javascript' import nord from '@shikijs/themes/nord' import { createHighlighterCore } from 'shiki/core' import { loadWasm } from 'shiki/engine/oniguruma' // import wasm as assets await loadWasm(import('shiki/onig.wasm')) export default { async fetch() { const highlighter = await createHighlighterCore({ themes: [nord], langs: [js], }) return new Response(highlighter.codeToHtml('console.log(\'shiki\');', { theme: 'nord', lang: 'js' })) }, } ``` -------------------------------- ### Create Fine-grained Shiki Bundle with Custom Languages and Themes Source: https://shiki.style/guide/bundles Illustrates how to build a fine-grained Shiki bundle by importing specific themes and languages directly. This method allows for maximum control over the bundled code, reducing size by only including necessary components. It utilizes `shiki/core` and `shiki/engine/oniguruma` to create a highlighter with custom configurations, including dynamic imports for themes and languages, and custom grammar loading. ```typescript // directly import the theme and language modules, only the ones you imported will be bundled. import nord from '@shikijs/themes/nord' // `shiki/core` entry does not include any themes or languages or the wasm binary. import { createHighlighterCore } from 'shiki/core' import { createOnigurumaEngine } from 'shiki/engine/oniguruma' const highlighter = await createHighlighterCore({ themes: [ // instead of strings, you need to pass the imported module nord, // or a dynamic import if you want to do chunk splitting import('@shikijs/themes/material-theme-ocean') ], langs: [ import('@shikijs/langs/javascript'), // shiki will try to interop the module with the default export () => import('@shikijs/langs/css'), // or a getter that returns custom grammar async () => JSON.parse(await fs.readFile('my-grammar.json', 'utf-8')) ], // `shiki/wasm` contains the wasm binary inlined as base64 string. engine: createOnigurumaEngine(import('shiki/wasm')) }) // optionally, load themes and languages after creation await highlighter.loadTheme(import('@shikijs/themes/vitesse-light')) const code = highlighter.codeToHtml('const a = 1', { lang: 'javascript', theme: 'material-theme-ocean' }) ``` -------------------------------- ### Synchronous Highlighter Initialization with Oniguruma Engine Source: https://shiki.style/guide/sync-usage Demonstrates how to use the Oniguruma engine synchronously by pre-resolving the engine promise. The highlighter instance is then created synchronously using the resolved engine. ```typescript 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 passed in, the rest can still be synced. }) const html = shiki.highlight('console.log(1)', { lang: 'js', theme: 'nord' }) ``` -------------------------------- ### Markdown with Twoslash Enabled Source: https://shiki.style/packages/vitepress Example of a markdown code block using the 'ts twoslash' syntax to enable TypeScript type hover information. The output shows how the code will be rendered with type annotations. ```markdown ```ts twoslash console.log('hello') // ^? ``` ``` ```typescript console . log ('hello') ``` -------------------------------- ### CSS Variables for Shiki Theme Source: https://shiki.style/guide/theme-colors Provides an example of CSS variables that can be defined in a stylesheet to customize the appearance of Shiki-highlighted code. This includes foreground, background, token-specific colors, and ANSI color codes. ```css :root { --shiki-foreground: #eeeeee; --shiki-background: #333333; --shiki-token-constant: #660000; --shiki-token-string: #770000; --shiki-token-comment: #880000; --shiki-token-keyword: #990000; --shiki-token-parameter: #aa0000; --shiki-token-function: #bb0000; --shiki-token-string-expression: #cc0000; --shiki-token-punctuation: #dd0000; --shiki-token-link: #ee0000; /* Only required if using lang: 'ansi' */ --shiki-ansi-black: #000000; --shiki-ansi-black-dim: #00000080; --shiki-ansi-red: #bb0000; --shiki-ansi-red-dim: #bb000080; --shiki-ansi-green: #00bb00; --shiki-ansi-green-dim: #00bb0080; --shiki-ansi-yellow: #bbbb00; --shiki-ansi-yellow-dim: #bbbb0080; --shiki-ansi-blue: #0000bb; --shiki-ansi-blue-dim: #0000bb80; --shiki-ansi-magenta: #ff00ff; --shiki-ansi-magenta-dim: #ff00ff80; --shiki-ansi-cyan: #00bbbb; --shiki-ansi-cyan-dim: #00bbbb80; --shiki-ansi-white: #eeeeee; --shiki-ansi-white-dim: #eeeeee80; --shiki-ansi-bright-black: #555555; --shiki-ansi-bright-black-dim: #55555580; --shiki-ansi-bright-red: #ff5555; --shiki-ansi-bright-red-dim: #ff555580; --shiki-ansi-bright-green: #00ff00; --shiki-ansi-bright-green-dim: #00ff0080; --shiki-ansi-bright-yellow: #ffff55; --shiki-ansi-bright-yellow-dim: #ffff5580; --shiki-ansi-bright-blue: #5555ff; --shiki-ansi-bright-blue-dim: #5555ff80; --shiki-ansi-bright-magenta: #ff55ff; --shiki-ansi-bright-magenta-dim: #ff55ff80; --shiki-ansi-bright-cyan: #55ffff; --shiki-ansi-bright-cyan-dim: #55ffff80; --shiki-ansi-bright-white: #ffffff; --shiki-ansi-bright-white-dim: #ffffff80; } ``` -------------------------------- ### Configure Shiki CLI Options Source: https://shiki.style/packages/cli Illustrates how to use command-line options to customize the Shiki CLI's behavior. Options include specifying the theme, overriding the auto-inferred language, and setting the output format to either ANSI or HTML. ```bash npx @shikijs/cli README.md --theme=nord ``` ```bash npx @shikijs/cli src/index.js --lang=ts ``` ```bash npx @shikijs/cli README.md --format=html ``` -------------------------------- ### Asynchronous Highlighting with Shiki Shorthands Source: https://shiki.style/guide/best-performance Use Shiki shorthands like `codeToHtml` for asynchronous highlighting to reduce startup time. This approach loads only the necessary themes and languages when `codeToHtml` is called, rather than upfront, which is beneficial when dealing with many themes and languages. ```typescript import { codeToHtml } from 'shiki' // Only `javascript` and `nord` will be loaded when calling `codeToHtml` const html = await codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' }) ``` -------------------------------- ### Usage of modern-monaco in HTML and JavaScript Source: https://shiki.style/packages/monaco Utilize modern-monaco by including the custom element `` in your HTML and initializing it with a Workspace object in your JavaScript. This setup allows for lazy initialization and easy file management within the editor. ```html ``` ```javascript // app.js import { lazy, Workspace } from 'modern-monaco' // create a workspace with initial files const workspace = new Workspace({ initialFiles: { 'index.html': `...`, 'main.js': `console.log('Hello, world!')`, }, entryFile: 'index.html', }) // initialize the editor lazily await lazy({ workspace }) // write a file and open it in the editor workspace.fs.writeFile('util.js', 'export function add(a, b) { return a + b; }') workspace.openTextDocument('util.js') ``` -------------------------------- ### Configure JavaScript Engine Options Source: https://shiki.style/guide/regex-engines Demonstrates how to enable forgiving mode for unsupported grammars and how to manually set the runtime target for compatibility. ```typescript const jsEngine = createJavaScriptRegexEngine({ forgiving: true }) const jsEngineTarget = createJavaScriptRegexEngine({ target: 'ES2018', // or 'auto' (default), 'ES2024', 'ES2025' }) ``` -------------------------------- ### Configure Matching Algorithm Source: https://shiki.style/packages/transformers Demonstrates how to toggle between v1 and v3 matching algorithms for transformer annotations. ```typescript const html = await codeToHtml(code, { lang: 'ts', theme: 'nord', transformers: [ transformerNotationDiff({ matchAlgorithm: 'v3', }), ], }); ``` -------------------------------- ### Apply Decorations with Negative Character Positions Source: https://shiki.style/guide/decorations This snippet illustrates using negative character positions to define decorations, where negative values count from the end of a line. This is useful for highlighting content relative to the end of a line, such as the entire first line in the example. The `DecorationItem` type is used to structure the decoration definition. ```typescript import { codeToHtml } from 'shiki' const item: DecorationItem = { start: { line: 0, character: 0 }, end: { line: 0, character: -1 }, properties: { class: 'highlighted-word' } } // This highlights the entire first line: const html = await codeToHtml(code, { theme: 'vitesse-light', lang: 'ts', decorations: [item] }) ``` -------------------------------- ### Cache Highlighter Instance with Shiki Core Source: https://shiki.style/guide/best-performance Create a Shiki highlighter instance once and reuse it for multiple highlighting operations to avoid the overhead of repeated creation. The `createHighlighterCore` function is used for this purpose. Remember to call `dispose()` when the instance is no longer needed to release resources. ```typescript import { createHighlighterCore } from 'shiki/core' const highlighterPromise = createHighlighterCore({ /* ... */ }) export async function highlightCode(code: string, lang: string) { const highlighter = await highlighterPromise return highlighter.codeToHtml(code, lang) } // To dispose: highlighter.dispose() ``` -------------------------------- ### Render Syntax Highlighting in React Server Components Source: https://shiki.style/packages/next Demonstrates how to use `codeToHtml` within an asynchronous React Server Component to render syntax-highlighted code blocks. This approach is ideal for server-side rendering as it avoids client-side bundle size overhead. ```tsx import type { BundledLanguage } from 'shiki' import { codeToHtml } from 'shiki' export default function Page() { return (
{[ 'console.log("Hello")', 'console.log("World")', ].join('\n')}
) } interface Props { children: string lang: BundledLanguage } async function CodeBlock(props: Props) { const out = await codeToHtml(props.children, { lang: props.lang, theme: 'github-dark' }) return
} ``` -------------------------------- ### Append Decorations within a Shiki Transformer Source: https://shiki.style/guide/decorations This example demonstrates how to dynamically generate and append decorations within a Shiki Transformer's `preprocess` hook. This allows for advanced use cases where decorations are determined based on the code content itself. Decorations are added to the `options.decorations` array, which must exist before pushing new decorations. ```typescript import { codeToHtml, ShikiTransformer } from 'shiki' const myTransformer: ShikiTransformer = { name: 'my-transformer', preprocess(code, options) { // Generate the decorations somehow const decorations = doSomethingWithCode(code) // Make sure the decorations array exists options.decorations ||= [] // Append the decorations options.decorations.push(...decorations) } } const html = await codeToHtml(code, { theme: 'vitesse-light', lang: 'ts', transformers: [ myTransformer ] }) ``` -------------------------------- ### Apply Decorations to Code Ranges (Line/Character) Source: https://shiki.style/guide/decorations This snippet demonstrates how to use the `codeToHtml` function from Shiki to apply custom decorations to specific lines and character ranges within a code block. Decorations are defined as an array of objects, each specifying start and end points (line and character) and properties (like CSS classes) to be applied. The `theme` and `lang` options are also specified. ```typescript import { codeToHtml } from 'shiki' const code = ` const x = 10 console.log(x) `.trim() const html = await codeToHtml(code, { theme: 'vitesse-light', lang: 'ts', decorations: [ { // line and character are 0-indexed start: { line: 1, character: 0 }, end: { line: 1, character: 11 }, properties: { class: 'highlighted-word' } } ] }) ``` -------------------------------- ### Asynchronous Rendering with markdown-it-async Source: https://shiki.style/packages/markdown-it Enabling asynchronous syntax highlighting by integrating with markdown-it-async, necessary when using Shiki shorthands. ```typescript import { fromAsyncCodeToHtml } from '@shikijs/markdown-it/async' import MarkdownItAsync from 'markdown-it-async' import { codeToHtml } from 'shiki' const md = MarkdownItAsync() md.use( fromAsyncCodeToHtml( codeToHtml, { themes: { light: 'vitesse-light', dark: 'vitesse-dark', } } ) ) const html = await md.renderAsync('# Title\n```ts\nconsole.log("Hello, World!")\n```') ``` -------------------------------- ### Load custom languages during initialization Source: https://shiki.style/guide/load-lang Demonstrates how to load a custom language by parsing a JSON TextMate grammar file and passing it to the 'langs' array during highlighter creation. ```typescript import { createHighlighter } from 'shiki' const myLang = JSON.parse(fs.readFileSync('my-lang.json', 'utf8')) const highlighter = await createHighlighter({ langs: [myLang], themes: ['vitesse-light'] }) const html = highlighter.codeToHtml(code, { lang: 'my-lang', theme: 'vitesse-light' }) ``` -------------------------------- ### Use fine-grained highlighter bundle Source: https://shiki.style/packages/rehype Shows how to use @shikijs/rehype/core to provide a custom highlighter instance, allowing for manual control over themes, languages, and engines. ```typescript import rehypeShikiFromHighlighter from '@shikijs/rehype/core' import { createHighlighterCore } from 'shiki/core' import { createOnigurumaEngine } from 'shiki/engine/oniguruma' import { unified } from 'unified' const highlighter = await createHighlighterCore({ themes: [import('@shikijs/themes/vitesse-light')], langs: [import('@shikijs/langs/javascript')], engine: createOnigurumaEngine(() => import('shiki/wasm')) }) const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypeShikiFromHighlighter, highlighter, { themes: { light: 'vitesse-light', dark: 'vitesse-dark' } }) .use(rehypeStringify) .processSync(await fs.readFile('./input.md')) ``` -------------------------------- ### Configure basic syntax highlighting Source: https://shiki.style/packages/rehype Demonstrates how to integrate @shikijs/rehype into a unified pipeline to process markdown files with syntax highlighting. ```typescript import rehypeShiki from '@shikijs/rehype' import rehypeStringify from 'rehype-stringify' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import { unified } from 'unified' const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypeShiki, { themes: { light: 'vitesse-light', dark: 'vitesse-dark', } }) .use(rehypeStringify) .process(await fs.readFile('./input.md')) ``` -------------------------------- ### Use transformerNotationHighlight Source: https://shiki.style/packages/transformers Demonstrates using [!code highlight] markers to emphasize specific lines or ranges of lines. ```markdown ```ts console.log('Not highlighted') console.log('Highlighted') // [!code highlight] console.log('Not highlighted') ``` ```ts // [!code highlight:3] console.log('Highlighted') console.log('Highlighted') console.log('not highlighted') ``` ``` -------------------------------- ### Integrate Twoslash with Shiki Source: https://shiki.style/packages/twoslash Basic implementation showing how to import the transformer and apply it to a Shiki codeToHtml call. ```typescript import { transformerTwoslash } from '@shikijs/twoslash' import { codeToHtml } from 'shiki' const html = await codeToHtml(`console.log()`, { lang: 'ts', theme: 'vitesse-dark', transformers: [ transformerTwoslash(), ], }) ``` -------------------------------- ### Configure markdown-it with Shiki Source: https://shiki.style/packages/markdown-it Basic implementation of the Shiki plugin within a markdown-it instance, defining light and dark themes. ```typescript import Shiki from '@shikijs/markdown-it' import MarkdownIt from 'markdown-it' const md = MarkdownIt() md.use(await Shiki({ themes: { light: 'vitesse-light', dark: 'vitesse-dark', } })) ```