• This repository has been archived on 07/Feb/2024
  • Stars
    star
    1,465
  • Rank 32,103 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 1 year ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A syntax highlighter based on TextMate grammars. ESM rewrite of shiki, with more features and capabilities.

Shikiji 式辞

NPM version

An ESM-focused rewrite of shiki, a beautiful syntax highlighter based on TextMate grammars. And a little bit more.

Changes

Install

npm install -D shikiji

Integrations

Usage

Bundled Usage

Basic usage is pretty much the same as shiki, only that some APIs are dropped, (for example, the singular theme options). Each theme and language file are dynamically imported ES modules, it would be better to list the languages and themes explicitly to have the best performance.

import { getHighlighter } from 'shikiji'

const shiki = await getHighlighter({
  themes: ['nord'],
  langs: ['javascript'],
})

// optionally, load themes and languages after creation
await shiki.loadTheme('vitesse-light')
await shiki.loadLanguage('css')

const code = shiki.codeToHtml('const a = 1', { lang: 'javascript', theme: 'vitesse-light' })

Unlike shiki, shikiji does not load any themes or languages when not specified.

import { getHighlighter } from 'shikiji'

const shiki = await getHighlighter()

shiki.codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' }) // throws error, `javascript` is not loaded

await shiki.loadLanguage('javascript') // load the language

If you want to load all themes and languages (not recommended), you can iterate all keys from bundledLanguages and bundledThemes.

import { bundledLanguages, bundledThemes, getHighlighter } from 'shikiji'

const shiki = await getHighlighter({
  themes: Object.keys(bundledThemes),
  langs: Object.keys(bundledLanguages),
})

shiki.codeToHtml('const a = 1', { lang: 'javascript' })

Or if your usage can be async, you can try the shorthands which will load the theme/language on demand.

Fine-grained Bundle

When importing shikiji, all the themes and languages are bundled as async chunks. Normally it won't be a concern to you as they are not being loaded if you don't use them. While in some cases you want to control what to bundle size, you can use the core and compose your own bundle.

// `shikiji/core` entry does not include any themes or languages or the wasm binary.
import { getHighlighterCore } from 'shikiji/core'

// `shikiji/wasm` contains the wasm binary inlined as base64 string.
import { getWasmInlined } from 'shikiji/wasm'

// directly import the theme and language modules, only the ones you imported will be bundled.
import nord from 'shikiji/themes/nord.mjs'

const shiki = await getHighlighterCore({
  themes: [
    // instead of strings, you need to pass the imported module
    nord,
    // or a dynamic import if you want to do chunk splitting
    import('shikiji/themes/vitesse-light.mjs')
  ],
  langs: [
    import('shikiji/langs/javascript.mjs'),
    // shikiji will try to interop the module with the default export
    () => import('shikiji/langs/css.mjs'),
    // or a getter that returns custom grammar
    async () => JSON.parse(await fs.readFile('my-grammar.json', 'utf-8'))
  ],
  loadWasm: getWasmInlined
})

// optionally, load themes and languages after creation
await shiki.loadTheme(import('shikiji/themes/vitesse-light.mjs'))

const code = shiki.codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' })

CJS Usage

shikiji is published as ESM-only to reduce the package size. It's still possible to use it in CJS, as Node.js supports importing ESM modules dynamically in CJS.

For example, the following ESM code:

// ESM
import { getHighlighter } from 'shikiji'

async function main() {
  const shiki = await getHighlighter({
    themes: ['nord'],
    langs: ['javascript'],
  })

  const code = shiki.codeToHtml('const a = 1', { lang: 'javascript' })
}

Can be written in CJS as:

// CJS
async function main() {
  const { getHighlighter } = await import('shikiji')

  const shiki = await getHighlighter({
    themes: ['nord'],
    langs: ['javascript'],
  })

  const code = shiki.codeToHtml('const a = 1', { lang: 'javascript' })
}

CDN Usage

To use shikiji in the browser via CDN, you can use esm.run or esm.sh.

<body>
  <div id="foo"></div>

  <script type="module">
    // be sure to specify the exact version
    import { codeToHtml } from 'https://esm.sh/[email protected]' 
    // or
    // import { codeToHtml } from 'https://esm.run/[email protected]' 

    const foo = document.getElementById('foo')
    foo.innerHTML = await codeToHtml('console.log("Hi, Shiki on CDN :)")', { lang: 'js', theme: 'vitesse-light' })
  </script>
</body>

It's quite efficient as it will only load the languages and themes on demand. For the code snippet above, only four requests will be fired (shikiji, shikiji/themes/vitesse-light.mjs, shikiji/langs/javascript.mjs, shikiji/wasm.mjs), with around 200KB data transferred in total.

Demo

Cloudflare Workers

Cloudflare Workers does not support initializing WebAssembly from binary data, so the default wasm build won't work. You need to upload the wasm as assets and import it directly.

Meanwhile, it's also recommended to use the Fine-grained Bundle approach to reduce the bundle size.

import { getHighlighterCore, loadWasm } from 'shikiji/core'
import nord from 'shikiji/themes/nord.mjs'
import js from 'shikiji/langs/javascript.mjs'

// import wasm as assets
import wasm from 'shikiji/onig.wasm'

// load wasm outside of `fetch` so it can be reused
await loadWasm(obj => WebAssembly.instantiate(wasm, obj))

export default {
  async fetch() {
    const highlighter = await getHighlighterCore({
      themes: [nord],
      langs: [js],
    })

    return new Response(highlighter.codeToHtml('console.log(\'shiki\');', { lang: 'js' }))
  },
}

Additional Features

Shorthands

In addition to the getHighlighter function, shikiji also provides some shorthand functions for simpler usage.

import { codeToHtml, codeToThemedTokens } from 'shikiji'

const code = await codeToHtml('const a = 1', { lang: 'javascript', theme: 'nord' })
const tokens = await codeToThemedTokens('<div class="foo">bar</div>', { lang: 'html', theme: 'min-dark' })

Currently supports:

  • codeToThemedTokens
  • codeToHtml
  • codeToHast

Internally they maintain a singleton highlighter instance and load the theme/language on demand. Different from shiki.codeToHtml, the codeToHtml shorthand function returns a Promise and lang and theme options are required.

Note: These are only available in the bundled usage, a.k.a the main shikiji entry. If you are using the fine-grained bundle, you can create your own shorthands using createSingletonShorthands or port it your own.

Light/Dark Dual Themes

shikiji added an experimental light/dark dual themes support. Different from markdown-it-shiki's approach which renders the code twice, shikiji's dual themes approach uses CSS variables to store the colors on each token. It's more performant with a smaller bundle size.

Changing the theme option in codeToHtml to options with light and dark key to generate with two themes.

import { getHighlighter } from 'shikiji'

const shiki = await getHighlighter({
  themes: ['nord', 'min-light'],
  langs: ['javascript'],
})

const code = shiki.codeToHtml('console.log("hello")', {
  lang: 'javascript',
  themes: {
    light: 'vitesse-light',
    dark: 'nord',
  }
})

The following HTML will be generated (demo preview):

<pre
  class="shiki shiki-themes min-light--nord"
  style="background-color: #ffffff;--shiki-dark-bg:#2e3440ff;color: #ffffff;--shiki-dark-bg:#2e3440ff"
  tabindex="0"
>
  <code>
    <span class="line">
      <span style="color:#1976D2;--shiki-dark:#D8DEE9">console</span>
      <span style="color:#6F42C1;--shiki-dark:#ECEFF4">.</span>
      <span style="color:#6F42C1;--shiki-dark:#88C0D0">log</span>
      <span style="color:#24292EFF;--shiki-dark:#D8DEE9FF">(</span>
      <span style="color:#22863A;--shiki-dark:#ECEFF4">&quot;</span>
      <span style="color:#22863A;--shiki-dark:#A3BE8C">hello</span>
      <span style="color:#22863A;--shiki-dark:#ECEFF4">&quot;</span>
      <span style="color:#24292EFF;--shiki-dark:#D8DEE9FF">)</span>
    </span>
  </code>
</pre>

To make it reactive to your site's theme, you need to add a short CSS snippet:

Query-based Dark Mode
@media (prefers-color-scheme: dark) {
  .shiki,
  .shiki span {
    color: var(--shiki-dark) !important;
    background-color: var(--shiki-dark-bg) !important;
    /* Optional, if you also want font styles */
    font-style: var(--shiki-dark-font-style) !important;
    font-weight: var(--shiki-dark-font-weight) !important;
    text-decoration: var(--shiki-dark-text-decoration) !important;
  }
}
Class-based Dark Mode
html.dark .shiki,
html.dark .shiki span {
  color: var(--shiki-dark) !important;
  background-color: var(--shiki-dark-bg) !important;
  /* Optional, if you also want font styles */
  font-style: var(--shiki-dark-font-style) !important;
  font-weight: var(--shiki-dark-font-weight) !important;
  text-decoration: var(--shiki-dark-text-decoration) !important;
}

Multiple Themes

It's also possible to support more than two themes. In the themes object, you can have an arbitrary number of themes, and specify the default theme with defaultColor option.

const code = shiki.codeToHtml('console.log("hello")', {
  lang: 'javascript',
  themes: {
    light: 'github-light',
    dark: 'github-dark',
    dim: 'github-dimmed',
    // any number of themes
  },

  // optional customizations
  defaultColor: 'light',
  cssVariablePrefix: '--shiki-'
})

A token would be generated like:

<span style="color:#1976D2;--shiki-dark:#D8DEE9;--shiki-dim:#566575">console</span>

And then update your CSS snippet to control then each theme taking effect. Here is an example:

Demo preview

Without Default Color

If you want to take full control of the colors, or avoid using !important to override, you can optionally disable the default color by setting defaultColor to false.

const code = shiki.codeToHtml('console.log("hello")', {
  lang: 'javascript',
  themes: {
    light: 'vitesse-light',
    dark: 'vitesse-dark',
  },
  defaultColor: false, // <--
})

With it, a token would be generated like:

<span style="--shiki-dark:#D8DEE9;--shiki-light:#2E3440">console</span>

In that case, the generated HTML would have no style out of the box, you need to add your own CSS to control the colors.

It's also possible to control the theme in CSS variables, for more, reference to the great research and examples by @mayank99 in this issue #6.

codeToHast

shikiji used hast to generate HTML. You can use codeToHast to generate the AST and use it with tools like unified.

const root = shiki.codeToHast('const a = 1', { lang: 'javascript', theme: 'nord' })

console.log(root)
{
  type: 'root',
  children: [
    {
      type: 'element',
      tagName: 'pre',
      properties: {
        class: 'shiki vitesse-light',
        style: 'background-color:#ffffff;color:#393a34',
        tabindex: '0'
      },
      children: [
        {
          type: 'element',
          tagName: 'code',
          properties: {},
          children: [
            {
              type: 'element',
              tagName: 'span',
              properties: { class: 'line' },
              children: [
                {
                  type: 'element',
                  tagName: 'span',
                  properties: { style: 'color:#AB5959' },
                  children: [ { type: 'text', value: 'const' } ]
                },
                {
                  type: 'element',
                  tagName: 'span',
                  properties: { style: 'color:#B07D48' },
                  children: [ { type: 'text', value: ' a' } ]
                },
                {
                  type: 'element',
                  tagName: 'span',
                  properties: { style: 'color:#999999' },
                  children: [ { type: 'text', value: ' =' } ]
                },
                {
                  type: 'element',
                  tagName: 'span',
                  properties: { style: 'color:#2F798A' },
                  children: [ { type: 'text', value: ' 1' } ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

Hast transformers

Since shikiji uses hast internally, you can use the transforms option to customize the generated HTML by manipulating the hast tree. You can pass custom functions to modify the tree for different types of nodes. For example:

const code = await codeToHtml('foo\bar', {
  lang: 'js',
  theme: 'vitesse-light',
  transforms: {
    code(node) {
      node.properties.class = 'language-js'
    },
    line(node, line) {
      node.properties['data-line'] = line
      if ([1, 3, 4].includes(line))
        node.properties.class += ' highlight'
    },
    token(node, line, col) {
      node.properties.class = `token:${line}:${col}`
    },
  },
})

Breaking Changes from Shiki

We take this chance to make some breaking changes that we think is beneficial for the future. We'd suggest you try to migration those changes if possible, as most of them should be straight forward. If your have very deep integration, you can try with our compatibility build shikiji-compat which aligns with shiki's current API.

As of [email protected]:

Hard Breaking Changes

Breaking changes applied to both shikiji and shikiji-compat:

  • CJS and IIFE builds are dropped. See CJS Usage and CDN Usage for more details.
  • codeToHtml uses hast internally. The generated HTML will be a bit different but should behavior the same.
  • css-variables theme is not supported. Use the dual themes approach instead.

Soft Breaking Changes

Breaking changes applies to shikiji, but shimmed by shikiji-compat:

  • Top level named export setCDN, loadLanguage, loadTheme, setWasm are dropped as they are not needed anymore.
  • BUNDLED_LANGUAGES, BUNDLED_THEMES are moved to shikiji/langs and shikiji/themes and renamed to bundledLanguages and bundledThemes respectively.
  • theme option for getHighlighter is dropped, use themes with an array instead.
  • Highlighter does not maintain an internal default theme context. theme option is required for codeToHtml and codeToThemedTokens.
  • .ansiToHtml is merged into .codeToHtml as a special language ansi. Use .codeToHtml(code, { lang: 'ansi' }) instead.
  • lineOptions is dropped in favor of the fully customizable transforms option.
  • LanguageRegistration's grammar field is flattened to LanguageRegistration itself, refer to the types for more details.

Bundle Size

You can inspect the bundle size in detail on pkg-size.dev/shikiji.

As of v0.5.0, measured at 17th, August 2023:

Bundle Size (minified) Size (gzip) Notes
shikiji 6 MB 1.2 MB includes all themes and languages as async chunks
shikiji/core 112 KB 35 KB no themes or languages, compose on your own
shikiji/wasm 623 KB 231 KB wasm binary inlined as base64 string

What's Next?

Shikiji is a usable exploration of improving the experience of using shiki in various of scenarios. It's intended to push some of the ideas back to shiki, and eventually, this package might not be needed. Before that, you can use it as a replacement for shiki if you have similar requirements. It would be great to hear your feedback and suggestions in the meantime!

License

MIT

More Repositories

1

vitesse

πŸ• Opinionated Vite + Vue Starter Template
TypeScript
8,522
star
2

ni

πŸ’‘ Use the right package manager
TypeScript
4,527
star
3

icones

⚑️ Icon Explorer with Instant searching, powered by Iconify
Vue
4,525
star
4

unplugin-vue-components

πŸ“² On-demand components auto importing for Vue
TypeScript
3,011
star
5

unocss

The instant on-demand atomic CSS engine.
TypeScript
2,990
star
6

unplugin-icons

🀹 Access thousands of icons as components on-demand universally.
TypeScript
2,793
star
7

vitesse-webext

⚑️ WebExtension Vite Starter Template
TypeScript
2,581
star
8

unplugin-auto-import

Auto import APIs on-demand for Vite, Webpack and Rollup
TypeScript
2,307
star
9

vscode-file-nesting-config

Config of File Nesting for VS Code
JavaScript
2,132
star
10

vue-starport

πŸ›° Shared component across routes with animations
TypeScript
1,744
star
11

vscode-settings

My VS Code settings and extensions
1,739
star
12

eslint-config

Anthony's ESLint config presets
JavaScript
1,605
star
13

vitesse-nuxt3

Vitesse for Nuxt 3 πŸ”πŸ’šβš‘οΈ
TypeScript
1,510
star
14

reactivue

πŸ™Š Use Vue Composition API in React components
TypeScript
1,415
star
15

taze

πŸ₯¦ A modern cli tool that keeps your deps fresh
TypeScript
1,233
star
16

vite-ssg

Static site generation for Vue 3 on Vite
TypeScript
1,198
star
17

handle

A Chinese Hanzi variation of Wordle - 汉字 Wordle
TypeScript
1,194
star
18

qrcode-toolkit

Anthony's QR Code Toolkit for AI generated QR Codes
Vue
1,111
star
19

case-police

🚨 Make the case correct, PLEASE!
TypeScript
1,098
star
20

vite-plugin-inspect

Inspect the intermediate state of Vite plugins
Vue
1,009
star
21

use

Things I am using
991
star
22

vitesse-lite

⛺️ Lightweight version of Vitesse
TypeScript
901
star
23

drauu

Headless SVG-based drawboard in browser.
TypeScript
817
star
24

broz

A simple, frameless browser for screenshots
JavaScript
745
star
25

iroiro

Beautiful Colors Lookup in CLI
TypeScript
735
star
26

retypewriter

Replay the steps of your changes at ease.
TypeScript
715
star
27

live-draw

A tool allows you to draw on screen real-time.
C#
706
star
28

sd-webui-qrcode-toolkit

Anthony's QR Toolkit for Stable Diffusion WebUI
JavaScript
640
star
29

changelogithub

Generate changelog for GitHub
TypeScript
613
star
30

vite-plugin-md

Markdown with Vue for Vite
TypeScript
602
star
31

vscode-smart-clicks

Smart selection with double clicks for VS Code.
TypeScript
601
star
32

unplugin-vue2-script-setup

πŸ’‘ Bring `<script setup>` to Vue 2.
TypeScript
567
star
33

sponsorkit

πŸ’– Toolkit for generating sponsors images πŸ˜„
TypeScript
550
star
34

eslint-flat-config-viewer

A visual tool to help you view and understand your ESLint Flat config.
Vue
549
star
35

unconfig

A universal solution for loading configurations.
TypeScript
524
star
36

utils

Collection of common JavaScript / TypeScript utils
TypeScript
493
star
37

100

My 100-day project of exploring design, compform, and new things.
Vue
491
star
38

v-lazy-show

Compile-time directive to lazy initialize v-show for Vue
TypeScript
487
star
39

antfu.me

My personal website
Markdown
463
star
40

raycast-multi-translate

A Raycast extension that translates text to multiple languages at once
TypeScript
454
star
41

vue-reuse-template

Define and reuse Vue template inside the component scope.
TypeScript
440
star
42

vite-node

Vite as Node.js runtime
JavaScript
428
star
43

vscode-browse-lite

πŸš€ An embedded browser in VS Code
TypeScript
425
star
44

vscode-vite

One step faster for Vite in VS Code ⚑️
TypeScript
404
star
45

vscode-theme-vitesse

πŸ• Vitesse theme for VS Code
TypeScript
395
star
46

starter-ts

Starter template for TypeScript library
TypeScript
386
star
47

vue-template-promise

Template as Promise in Vue
TypeScript
373
star
48

vue-global-api

Use Vue Composition API globally
TypeScript
331
star
49

vue-router-better-scroller

Enhanced scroll behavior for Vue Router
TypeScript
327
star
50

qr-scanner-wechat

QR Code scanner in JS with Open CV and WeChat's Algorithm
JavaScript
322
star
51

starter-vscode

Starter template for VS Code Extension
TypeScript
299
star
52

vscode-iconify

πŸ™‚ Iconify IntelliSense for VS Code
TypeScript
294
star
53

1990-script

Make your GitHub history back to 1990
Shell
293
star
54

p

Toolkit for managing multiple promises
TypeScript
284
star
55

wenyan-lang-vscode

文言 Wenyan Lang for VS Code
TypeScript
277
star
56

pnpm-patch-i

A better and interactive pnpm patch
TypeScript
265
star
57

fsxx

File system in zx style
JavaScript
262
star
58

birpc

Message-based two-way remote procedure call.
TypeScript
245
star
59

vue-minesweeper

A tiny minesweeper clone in Vue 3
TypeScript
242
star
60

contribute

Contribution guide for my projects
231
star
61

purge-icons

🎐 Bundles icons on demand
TypeScript
229
star
62

vscode-open-in-github-button

Add a button to go to the GitHub on the status bar.
TypeScript
224
star
63

github-doorcat

😼 Supercharges GitHub navbar for fast navigation [WIP]
TypeScript
214
star
64

vscode-goto-alias

Go to Definition following alias redirections.
TypeScript
211
star
65

refined-github-notifications

UserScript that enhances the GitHub Notifications
JavaScript
208
star
66

eslint-plugin-command

Comment-as-command for one-off codemod with ESLint.
TypeScript
195
star
67

nuxt-server-fn

Server functions in client for Nuxt 3
TypeScript
194
star
68

magic-string-stack

magic-string with the capability of committing changes.
TypeScript
190
star
69

vscode-array-index-inlay

Show array index inlay hints for large arrays for VS Code
TypeScript
185
star
70

eslint-typegen

Generate types from ESLint rule schemas, with auto-completion and type-checking for rule options.
TypeScript
185
star
71

prism-theme-vars

A customizable Prism.js theme using CSS variables
CSS
178
star
72

what-time

What time works for you?
Vue
177
star
73

esbuild-node-loader

Transpile TypeScript to ESM with Node.js loader.
JavaScript
175
star
74

userscript-clean-twitter

Bring back the peace on Twitter
JavaScript
174
star
75

vitesse-nuxt-bridge

πŸ• Vitesse experience for Nuxt 2 and Vue 2
Vue
174
star
76

vscode-icons-carbon

Carbon Visual Studio Code product icon theme
TypeScript
170
star
77

talks

Slides & code for my talks
Vue
170
star
78

fs-spy

Monitoring fs accessing for Node process
TypeScript
166
star
79

vite-plugin-glob

The design experiment for import.meta.glob from Vite.
TypeScript
164
star
80

diff-match-patch-es

ESM and TypeScript rewrite of Google's diff-match-patch for JavaScript
TypeScript
159
star
81

vite-plugin-optimize-persist

Persist dynamically analyzed dependencies optimization
TypeScript
155
star
82

eslint-ts-patch

Support loading eslint.config.mjs and eslint.config.ts as flat config files for ESLint.
JavaScript
155
star
83

markdown-it-github-alerts

Support GitHub-style alerts for markdown-it
TypeScript
153
star
84

regex-doctor

Monitor your RegExp consumption and provide suggestions to improve performance.
TypeScript
152
star
85

v-dollar

jQuery-like Vue Reactivity API
TypeScript
146
star
86

.github

The default community health files for all my repos on GitHub
146
star
87

p5i

p5.js, but with more friendly instance mode APIs
TypeScript
139
star
88

vscode-pnpm-catalog-lens

Show versions inline for PNPM catalog: field
TypeScript
136
star
89

magic-string-extra

Extended magic-string with extra utilities
TypeScript
131
star
90

export-size

Analysis bundle cost for each export of a package
TypeScript
130
star
91

eslint-plugin-format

Format various languages with formatters in ESLint
TypeScript
129
star
92

local-pkg

Get information on local packages.
TypeScript
126
star
93

vite-plugin-restart

Custom files/globs to restart Vite server
TypeScript
124
star
94

pkg-exports

Get exports of an local npm package.
TypeScript
118
star
95

qr-verify

A CLI to verify scannable QR Code in batch
TypeScript
114
star
96

eslint-plugin-antfu

Anthony extended ESLint rules.
TypeScript
114
star
97

install-pkg

Install package programmatically.
TypeScript
114
star
98

deploy-check

WIP, Prevent runtime errors earlier in CI
TypeScript
113
star
99

fast-npm-meta

A lightweight API server to get npm package metadata, resolve the latest versions on server, and batch multiple package resolutions in one request.
TypeScript
110
star
100

markdown-it-mdc

MDC (Markdown Components) syntax for markdown-it.
TypeScript
106
star