Fumadocs 最佳实践指南

深入探讨 Fumadocs 文档框架的最佳实践和高级用法

Back

Fumadocs 最佳实践指南

Fumadocs 是一个现代化的文档框架,基于 Next.js 构建,专为技术文档而设计。本文将分享我们在使用 Fumadocs 过程中积累的最佳实践。

为什么选择 Fumadocs?

优势对比

与其他文档框架相比,Fumadocs 具有以下优势:

特性FumadocsDocusaurusVitePress
框架基础Next.jsReactVue
TypeScript✅ 原生支持✅ 支持✅ 支持
性能⚡ 极佳🚀 良好⚡ 极佳
自定义性🎨 高度灵活🔧 中等🎯 适中
SEO📈 优秀📈 优秀📈 优秀

核心特性

  • MDX 支持: 在 Markdown 中嵌入 React 组件
  • 代码高亮: 基于 Shiki 的语法高亮
  • 搜索功能: 内置全文搜索
  • 国际化: 多语言支持
  • 主题系统: 灵活的主题定制

项目结构最佳实践

文件组织

content/
├── docs/
│   ├── getting-started/
│   │   ├── index.mdx
│   │   ├── installation.mdx
│   │   └── meta.json
│   ├── api/
│   │   ├── authentication.mdx
│   │   ├── endpoints/
│   │   └── meta.json
│   └── index.mdx
├── blog/
│   ├── welcome.mdx
│   └── best-practices.mdx
└── meta.json

内容配置

// source.config.ts
export const docs = defineDocs({
  docs: {
    async: true,
    schema: frontmatterSchema.extend({
      index: z.boolean().default(false),
      category: z.string().optional(),
      tags: z.array(z.string()).optional(),
    }),
  },
  meta: {
    schema: metaSchema.extend({
      description: z.string().optional(),
      icon: z.string().optional(),
    }),
  },
});

MDX 增强功能

自定义组件

创建可重用的 MDX 组件:

// components/mdx/callout.tsx
interface CalloutProps {
  type?: 'info' | 'warning' | 'error';
  children: React.ReactNode;
}

export function Callout({ type = 'info', children }: CalloutProps) {
  return (
    <div className={`callout callout-${type}`}>
      {children}
    </div>
  );
}

在 MDX 中使用:

<Callout type="warning">
这是一个警告信息。
</Callout>

代码块增强

// source.config.ts
export default defineConfig({
  mdxOptions: {
    rehypeCodeOptions: {
      themes: {
        light: 'catppuccin-latte',
        dark: 'catppuccin-mocha',
      },
      transformers: [
        transformerTwoslash({
          typesCache: createFileSystemTypesCache(),
        }),
      ],
    },
  },
});

数学公式支持

# 数学公式示例

行内公式:$E = mc^2$

块级公式:
$$
\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}
$$

性能优化策略

懒加载配置

rehypeCodeOptions: {
  lazy: true, // 启用懒加载
  experimentalJSEngine: true, // 使用实验性 JS 引擎
}

内容分割

合理组织内容,避免单个页面过大:

  • 将长文档分割成多个子页面
  • 使用 meta.json 组织导航结构
  • 通过标签和分类管理内容

图片优化

import Image from 'next/image';

<Image
  src="/images/architecture.png"
  alt="系统架构图"
  width={800}
  height={600}
  placeholder="blur"
/>

SEO 优化

Meta 信息

---
title: 页面标题
description: 页面描述,用于搜索引擎优化
keywords: [关键词1, 关键词2]
---

结构化数据

// app/docs/[...slug]/page.tsx
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const page = source.getPage(params.slug);
  
  return {
    title: page?.data.title,
    description: page?.data.description,
    keywords: page?.data.keywords,
    openGraph: {
      title: page?.data.title,
      description: page?.data.description,
      images: [page?.data.image].filter(Boolean),
    },
  };
}

高级功能

自定义搜索

// lib/search.ts
import { createSearchAPI } from 'fumadocs-core/search-api';

export const searchAPI = createSearchAPI('advanced', {
  indexes: source.getPages().map((page) => ({
    title: page.data.title,
    structuredData: page.data.structuredData,
    id: page.url,
    url: page.url,
  })),
});

国际化支持

// source.config.ts
export const i18n = {
  defaultLanguage: 'zh',
  languages: ['zh', 'en'],
};

主题定制

/* global.css */
:root {
  --fd-primary: 200 100% 50%;
  --fd-background: 0 0% 100%;
  --fd-foreground: 240 10% 3.9%;
  --fd-muted: 240 4.8% 95.9%;
}

.dark {
  --fd-background: 240 10% 3.9%;
  --fd-foreground: 0 0% 98%;
  --fd-muted: 240 3.7% 15.9%;
}

部署和维护

构建优化

// next.config.ts
const config = {
  experimental: {
    optimizePackageImports: ['fumadocs-ui', 'lucide-react'],
  },
  // 静态导出配置
  output: 'export',
  trailingSlash: true,
};

内容管理工作流

  1. 内容创作: 使用 MDX 编写文档
  2. 本地预览: npm run dev 实时预览
  3. 构建验证: npm run build 验证构建
  4. 部署: 自动化部署到 CDN

监控和分析

// app/layout.tsx
export default function RootLayout({ children }: LayoutProps) {
  return (
    <html lang="zh">
      <body>
        {children}
        {/* Google Analytics */}
        <Analytics />
      </body>
    </html>
  );
}

常见问题和解决方案

构建性能问题

问题: 大量文档导致构建时间过长

解决方案:

  • 启用 async: true 进行异步处理
  • 使用增量构建
  • 合理分割内容

搜索功能优化

问题: 搜索结果不够准确

解决方案:

  • 优化索引结构
  • 添加相关标签和关键词
  • 使用结构化数据

样式冲突

问题: 自定义样式与主题冲突

解决方案:

  • 使用 CSS 变量进行主题定制
  • 遵循 Fumadocs 的样式约定
  • 使用 Tailwind CSS 进行样式管理

总结

Fumadocs 为构建现代化文档网站提供了强大的基础设施。通过遵循这些最佳实践,您可以:

  • 📚 创建结构清晰的文档
  • 🚀 获得优秀的性能表现
  • 🎨 实现高度的定制化
  • 📈 优化搜索引擎表现

持续关注 Fumadocs 的更新,并根据项目需求调整配置,将帮助您构建出色的文档体验。

Written by

文档团队

At

Thu Jan 25 2024