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

Mermaid 图表

使用 beautiful-mermaid 在文档中渲染 Mermaid 图表

简介

Fumadocs 没有内置的 Mermaid 封装, 推荐直接使用 mermaid 或第三方渲染器.

这里使用 beautiful-mermaid 方案, 它是第三方 Mermaid 渲染器, 支持服务端渲染, 无需客户端 JS.

现场演示

下面是一个架构图的实时渲染:

Consumers Services API Gateway Mobile app Web app Node.js client REST API GraphQL API SOAP API

一个简单的流程图:

开始 判断 执行 A 执行 B 结束

安装

pnpm add beautiful-mermaid

创建 Mermaid 组件

创建 components/mdx/mermaid.tsx:

import { CodeBlock, Pre } from 'fumadocs-ui/components/codeblock';
import { renderMermaidSVG } from 'beautiful-mermaid';

export async function Mermaid({ chart }: { chart: string }) {
  try {
    const svg = renderMermaidSVG(chart, {
      bg: 'var(--color-fd-background)',
      fg: 'var(--color-fd-foreground)',
      interactive: true,
      transparent: true,
    });

    return <div dangerouslySetInnerHTML=\{\{ __html: svg }} />;
  } catch {
    return (
      <CodeBlock title="Mermaid">
        <Pre>{chart}</Pre>
      </CodeBlock>
    );
  }
}

注册 MDX 组件

components/mdx.tsx 中注册:

import defaultMdxComponents from 'fumadocs-ui/mdx';
import { Mermaid } from '@/components/mdx/mermaid';
import type { MDXComponents } from 'mdx/types';

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

使用方式

在 MDX 文件中使用 <Mermaid> 组件:

<Mermaid
  chart={`
graph TD;
subgraph AA [Consumers]
A[Mobile app];
B[Web app];
C[Node.js client];
end
subgraph BB [Services]
E[REST API];
F[GraphQL API];
G[SOAP API];
end
Z[GraphQL API];
A --> Z;
B --> Z;
C --> Z;
Z --> E;
Z --> F;
Z --> G;
  `}
/>

作为代码块使用

可以在 source.config.ts 中添加 remarkMdxMermaid 插件, 将 mermaid 代码块自动转换为 Mermaid 组件:

import { remarkMdxMermaid } from 'fumadocs-core/mdx-plugins';
import { defineConfig } from 'fumadocs-mdx/config';

export default defineConfig({
  mdxOptions: {
    remarkPlugins: [remarkMdxMermaid],
  },
});

然后直接用代码块:

graph TD;
  A-->B;
  A-->C;

注意事项

  • beautiful-mermaid 支持服务端渲染, 无需客户端 JS
  • 如果渲染失败, 会回退显示原始 mermaid 代码
  • 支持亮色/暗色模式自动切换 (var(--color-fd-background) / var(--color-fd-foreground))
  • 官方方案 (mermaid + next-themes) 需要客户端渲染, 需要额外配置

更多详情见 Fumadocs 文档.

On this page