Skip to content

shiki-twoslash

@vuepress/shiki-twoslash

Twoslash integration for @vuepress/plugin-shiki.

Twoslash runs the TypeScript compiler on a code sample, so that its types, errors and completions are known at build time. This package turns a Twoslash result into the markup of the code sample, and renders the information as a popup that appears when the reader hovers the sample. It is the optional dependency that @vuepress/plugin-shiki loads when its twoslash option is enabled.

Usage

npm i @vuepress/shiki-twoslash@next

It is only used by @vuepress/plugin-shiki, which does not install it by default to keep the site small. Enable the feature in the plugin after installing the package:

.vuepress/config.ts
import { shikiPlugin } from '@vuepress/plugin-shiki'

export default {
  plugins: [
    shikiPlugin({
      twoslash: true,
    }),
  ],
}

The twoslash option also accepts an object of the options below, and the code blocks that should be checked must carry the twoslash marker in their info string. See Shiki > Twoslash Support.

Guide

Running Twoslash on a code block

A code block is checked when its info string has the twoslash marker, which is matched by the explicitTrigger option by default:

```ts twoslash
const a = 1
const b = 23

console.log(a + b)
```

The transformer only runs on ts, tsx, js, jsx, json and vue code blocks. A Vue block is compiled by twoslash-vue first, so the script of a single file component can be checked as well.

The transformer disables the v-pre handling of the triggered blocks, because the markup of the popups must be compiled by Vue, so do not add the :v-pre marker to a Twoslash block. The braces of the generated markup are escaped, so that Vue does not read them as interpolations.

Resolving the types

Twoslash needs the TypeScript compiler options of the site. The transformer starts from the default Twoslash options, adds the baseUrl of the current working directory, and merges the paths of the tsconfig.json of the working directory with the ones of the twoslashOptions option, so that the aliases of a site resolve in its code samples:

.vuepress/config.ts
import { shikiPlugin } from '@vuepress/plugin-shiki'

export default {
  plugins: [
    shikiPlugin({
      twoslash: {
        twoslashOptions: {
          compilerOptions: {
            lib: ['es2015', 'dom'],
          },
        },
      },
    }),
  ],
}

A Twoslash error fails the build in CI and in production, and is logged without failing it in the dev server. The throws option forces either behavior.

Caching the resolved types

Twoslash is slow, so the result of every code sample can be cached on the file system and reused until the sample changes. createFileSystemTypesCache() writes the result of a sample into a JSON file named by the hash of its code:

.vuepress/config.ts
import { shikiPlugin } from '@vuepress/plugin-shiki'
import { createFileSystemTypesCache } from '@vuepress/shiki-twoslash'
import { path } from 'vuepress/utils'

export default {
  plugins: [
    shikiPlugin({
      twoslash: {
        typesCache: createFileSystemTypesCache({
          dir: path.resolve(import.meta.dirname, '.cache/twoslash'),
        }),
      },
    }),
  ],
}

The directory is created when the cache is initialized, so it does not have to exist. Remember to ignore it in the version control.

Rendering the popups

The popups are rendered as FloatingVue menus, so the client config of the plugin has to register the component and import the styles of both FloatingVue and the package:

src/client/config.ts
import { enhanceTwoslash } from '@vuepress/shiki-twoslash/client'
import { defineClientConfig } from 'vuepress/client'

import '@vuepress/shiki-twoslash/twoslash.css'

export default defineClientConfig({
  enhance({ app }) {
    enhanceTwoslash(app)
  },
})

enhanceTwoslash() registers FloatingVue with the themes that the renderer uses: twoslash for the hover and query popups, and twoslash-completion for the completion list. Since a popup is positioned when it is opened, the poppers are recomputed when a code tab is switched.

Node API

createTwoslashTransformer

optionsShikiTwoslashOptions

The options of the transformer, see Options.

It returns the ShikiTransformer of the package, named vuepress:twoslash, which runs Twoslash on the triggered code blocks and renders its result with rendererFloatingVue(). It is an async function, because it reads the tsconfig.json of the working directory before creating the transformer.

It is loaded by @vuepress/plugin-shiki itself, so you only need it when you write your own highlighter integration.

rendererFloatingVue

optionsTwoslashFloatingVueRendererOptions

The renderer options, i.e. the RendererRichOptions of Twoslash and the floatingVue options below.

It returns the renderer of the package, i.e. a rendererRich that renders every popup as a FloatingVue menu with the theme names that enhanceTwoslash() registers. An error of a code sample is rendered on its line by default.

createFileSystemTypesCache

dirRequiredstring

The directory that stores the cached results.

It returns a TwoslashTypesCache, which reads and writes the result of a code sample as <hash>.json in the directory. The directory is created by the init() hook of the cache.

resolveTypeScriptPaths

It reads the compilerOptions.paths of the tsconfig.json of the working directory and resolves them against its baseUrl. It returns null when the file does not exist or cannot be parsed, and a TypeScriptPaths, i.e. a Record<string, string[]>, otherwise.

Client API

enhanceTwoslash

appRequiredApp

The Vue app of the site.

It registers the FloatingVue component and the themes of the package into the app, and imports the styles of FloatingVue. It must be called once in the client config of the plugin, together with the import of @vuepress/shiki-twoslash/twoslash.css.

Options

ShikiTwoslashOptions

explicitTriggerRegExp | boolean
Defaulttrue

Whether Twoslash only runs on the code blocks that carry its marker. true matches the twoslash marker, a RegExp replaces the marker and false runs Twoslash on every supported code block.

twoslashOptionsTransformerTwoslashOptions['twoslashOptions'] & VueSpecificOptions

The options of Twoslash itself, merged after its defaults. Its compilerOptions are merged with the resolved paths of the site.

typesCacheTwoslashTypesCache

The cache of the resolved types, e.g. the one returned by createFileSystemTypesCache().

throwsboolean

Whether a Twoslash error fails the build. It defaults to process.env.CI or the production environment, so an error fails the build in CI and in a production build.

errorRendering'line' | 'hover'
Default'line'

Where the error of a code sample is rendered, inherited from RendererRichOptions. 'line' marks the line, and 'hover' only shows it in the popup.

The options also extend TransformerTwoslashOptions of @shikijs/twoslash and RendererRichOptions of its rich renderer.

TwoslashFloatingVueOptions

classCopyIgnorestring
Default'vp-copy-ignore'

The class of the elements that the copy code button must ignore.

classFloatingPanelstring
Default'twoslash-floating'

The class of the floating panel of a popup.

classCodestring
Default'vp-code'

The class of the code elements of a popup.

classMarkdownstring
Default''

The class of the markdown elements of a popup.

attrMarkdownstring
Default'vp-content'

The attribute that marks the markdown content of a popup.

floatingVueThemestring
Default'twoslash'

The FloatingVue theme of the hover and query popups.

floatingVueThemeQuerystring
Default'twoslash-query'

The FloatingVue theme of the query popups.

floatingVueThemeCompletionstring
Default'twoslash-completion'

The FloatingVue theme of the completion popups.

They are passed as the floatingVue option of ShikiTwoslashOptions and TwoslashFloatingVueRendererOptions.

MIT Licensed