Markdown
Twoslash
在 Fumadocs 中集成 TypeScript Twoslash
安装
利用 Shiki 内置的 Twoslash 集成:
npm install fumadocs-twoslash twoslashNext.js 配置
对于 Next.js 项目,在 next.config.mjs 中外部化依赖:
serverExternalPackages: ['typescript', 'twoslash']Shiki 设置
在 source.config.ts 中添加 transformer:
import { transformerTwoslash } from 'fumadocs-twoslash';
import { rehypeCodeDefaultOptions } from 'fumadocs-core/mdx-plugins';
export default defineConfig({
mdxOptions: {
rehypeCodeOptions: {
transformers: [
...(rehypeCodeDefaultOptions.transformers ?? []),
transformerTwoslash(),
],
langs: ['js', 'jsx', 'ts', 'tsx'],
},
},
});样式
在 Tailwind 配置中导入 CSS(需要 Tailwind CSS v4):
@import 'fumadocs-twoslash/twoslash.css';MDX 组件
在 components/mdx.tsx 中注册 Twoslash 组件:
import * as Twoslash from 'fumadocs-twoslash/ui';
import defaultComponents from 'fumadocs-ui/mdx';
export function getMDXComponents(components?: MDXComponents) {
return {
...defaultComponents,
...Twoslash,
...components,
} satisfies MDXComponents;
}使用
在代码块中添加 twoslash 元字符串:
```ts twoslash
console.log('Hello World');
```可选缓存
启用文件系统缓存:
import { createFileSystemTypesCache } from 'fumadocs-twoslash/cache-fs';
transformerTwoslash({
typesCache: createFileSystemTypesCache(),
});Twoslash 标记
请参阅 Twoslash 标记文档 了解高级功能,包括类型推断显示、错误标记和代码裁剪。