Fumadocs

Tanstack Start

支持在您的 Tanstack Start + Fumadocs 应用上使用 i18n 路由。

设置

在文件中定义 i18n 配置,我们将在本指南中使用 @/lib/i18n 导入它。

src/lib/i18n.ts
import { defineI18n } from 'fumadocs-core/i18n';

export const i18n = defineI18n({
  defaultLanguage: 'en',
  languages: ['cn', 'en'],
});

有关 i18n 配置的可用选项

路由

routes 下创建一个 $lang 目录,并将所有页面移动到其中。

index.tsx
docs/$.tsx
search.ts

<RootProvider /> 提供 UI 翻译和其他配置,英文翻译用作后备。

src/routes/__root.tsx
import { HeadContent, Scripts, useParams } from '@tanstack/react-router';
import * as React from 'react';
import { RootProvider } from 'fumadocs-ui/provider/base';
import { TanstackProvider } from 'fumadocs-core/framework/tanstack';
import { defineI18nUI } from 'fumadocs-ui/i18n';
import { i18n } from '@/lib/i18n';

const { provider } = defineI18nUI(i18n, {
  translations: {
    cn: {
      displayName: 'Chinese',
      search: 'Translated Content',
    },
    en: {
      displayName: 'English',
    },
  },
});

function RootDocument({ children }: { children: React.ReactNode }) {
  const { lang } = useParams({ strict: false });

  return (
    <html suppressHydrationWarning>
      <head>
        <HeadContent />
      </head>
      <body className="flex flex-col min-h-screen">
        <TanstackProvider>
          <RootProvider
            i18n={provider(lang)}
          >
            {children}
          </RootProvider>
        </TanstackProvider>
        <Scripts />
      </body>
    </html>
  );
}

传递语言

locale 参数添加到 baseOptions() 中,并将 i18n 包含在 props 中:

src/lib/layout.shared.tsx
import { i18n } from '@/lib/i18n';
import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';

export function baseOptions(locale: string): BaseLayoutProps {
  return {
    i18n,
    // different props based on `locale`
  };
}

在您的页面和布局中将语言传递给 Fumadocs。

import { i18n } from '@/lib/i18n';
import { loader } from 'fumadocs-core/source';

export const source = loader({
  i18n,
  // other options
});

搜索

在您的搜索解决方案上配置 i18n。

  • 内置搜索 (Orama): 参阅国际化
  • 云解决方案 (例如 Algolia): 它们通常有官方的多语言支持。

编写文档

参阅 i18n 路由 以了解如何为特定语言创建页面。

导航

Fumadocs 仅处理其自身布局的导航(例如侧边栏)。 对于其他位置,您可以使用 useParams 钩子从 URL 获取语言。

import { Link, useParams } from '@tanstack/react-router';

const { lang } = useParams({ from: '/$lang/' });

<Link
  to="/$lang/docs/$"
  params={{
    lang,
    _splat: '',
  }}
>
  Open Docs
</Link>;

此外,fumadocs-core/dynamic-link 组件支持动态 href,您可以使用它来附加语言前缀。 它对于 Markdown/MDX 内容很有用。

content.mdx
import { DynamicLink } from 'fumadocs-core/dynamic-link';

<DynamicLink href="/[lang]/another-page">This is a link</DynamicLink>

How is this guide?

Last updated on