Dimitri's Journal工作日记 & 文档
示例

Twoslash

在代码块中使用 TypeScript Twoslash 编译器提示

简介

Twoslash 是 Shiki 的 TypeScript 集成, 可以在代码块中显示类型信息、错误提示、补全建议等编译器级别的信息.

Fumadocs 通过 fumadocs-twoslash 提供 Twoslash 支持.

安装

pnpm add fumadocs-twoslash twoslash

如果是 Next.js, 需要在 next.config.mjs 中添加:

const config = {
  reactStrictMode: true,
  serverExternalPackages: ['typescript', 'twoslash'],
};

配置

1. 添加 Shiki 转换器

source.config.ts 中添加 transformerTwoslash:

import { defineConfig } from 'fumadocs-mdx/config';
import { transformerTwoslash } from 'fumadocs-twoslash';
import { rehypeCodeDefaultOptions } from 'fumadocs-core/mdx-plugins';

export default defineConfig({
  mdxOptions: {
    rehypeCodeOptions: {
      themes: {
        light: 'github-light',
        dark: 'github-dark',
      },
      transformers: [
        ...(rehypeCodeDefaultOptions.transformers ?? []),
        transformerTwoslash(),
      ],
      // 重要: Shiki 不支持在 Twoslash 弹窗中懒加载语言
      // 确保首先定义常用语言
      langs: ['js', 'jsx', 'ts', 'tsx'],
    },
  },
});

2. 添加样式

global.css 中添加:

@import 'fumadocs-twoslash/twoslash.css';

3. 注册 MDX 组件

components/mdx.tsx 中:

import * as Twoslash from 'fumadocs-twoslash/ui';
import defaultComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';

export function getMDXComponents(components?: MDXComponents) {
  return {
    ...defaultComponents,
    ...Twoslash,
    ...components,
  } satisfies MDXComponents;
}

使用

在代码块中添加 twoslash 标记:

.('Hello World');

类型查询 ^?

const a = 'Hello World';
const a: "Hello World"
.();

错误提示

const  = '123';
a = 132;
Cannot assign to 'a' because it is a constant.

补全建议

.g
  • group
  • groupCollapsed
  • groupEnd
g
Property 'gg' does not exist on type 'Console'.

类型定义

type  = {
  : string;
};
const :  = { : 'Hello World' };

缓存

可选开启文件系统缓存, 加速重复构建:

import { transformerTwoslash } from 'fumadocs-twoslash';
import { createFileSystemTypesCache } from 'fumadocs-twoslash/cache-fs';

transformerTwoslash({
  typesCache: createFileSystemTypesCache(),
});

注意事项

  • Twoslash 必须在构建时运行, 不能在纯客户端环境使用
  • 需要 typescripttwoslash 包作为外部依赖
  • 缓存可以显著加快构建速度
  • 支持所有标准的 Twoslash 注释: ^? (类型查询), ^| (补全), 错误提示等

更多 Twoslash 语法见 Twoslash 文档.

On this page