Fumadocs rebuilt on Hamur, the original is fumadocs.dev
跳至內容
Fumadocs

國際化

讓您的 Waku 文件支援多種語言。

Fumadocs 能以多種語言呈現您的文件及其 UI,應用程式的其他部分則可搭配任何 i18n 函式庫使用。

若要在應用程式中設定 Fumadocs 並啟用 i18n,請執行:

npx @fumadocs/cli init --i18n

若要在現有的 Fumadocs 專案中加入 i18n,請依照下列步驟操作。

設定

定義語言

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

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

Waku 不支援選用的路由區段,因此每個 URL 都會帶有語系前綴,例如 /en/docs。

如需其他選項 (例如備用語言) ,請參閱設定。

新增語系路由區段

請將您的頁面移至 [lang] 區段:

_layout.tsx
_api/api/search.ts
index.tsx
docs/[...slugs].tsx

翻譯 UI

請在版面配置選項旁定義 UI 翻譯,並讓 baseOptions() 接收語系參數:

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

export const translations = i18n
  .translations()
  .extend(uiTranslations())
  .add({
    cn: {
      // 語言切換器中顯示的名稱
      displayName: '中文',
      'Search(search trigger)': '搜尋文檔',
    },
  });

export function baseOptions(locale: string): BaseLayoutProps {
  return {
    nav: {
      title: 'My App',
      url: `/${locale}`,
    },
  };
}

使用語言包即可一次翻譯整個 UI。

將翻譯傳入 <RootProvider />:

src/components/provider.tsx
'use client';
import type { ReactNode } from 'react';
import { useRouter } from 'waku/router/client';
import { RootProvider } from 'fumadocs-ui/provider/waku';
import { i18nProvider } from 'fumadocs-ui/i18n';
import { i18n } from '@/lib/i18n';
import { translations } from '@/lib/layout.shared';

export function Provider({ children }: { children: ReactNode }) {
  // 路徑的第一個區段
  const lang = useRouter().path.split('/')[1] || i18n.defaultLanguage;

  return <RootProvider i18n={i18nProvider(translations, lang)}>{children}</RootProvider>;
}

傳入語系

將您的 i18n 設定加入 loader():

lib/source.ts
import { i18n } from '@/lib/i18n';

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

接著將語系傳入您的頁面。Waku 的版面配置不會收到語系,因此請改在頁面中算繪 <HomeLayout /> 與 <DocsLayout />:

src/pages/[lang]/index.tsx
export default function Home({ lang }: PageProps<'/[lang]'>) {
  return <HomeLayout {...baseOptions(lang)}>{/* ... */}</HomeLayout>;
}

export async function getConfig() {
  return {
    render: 'static',
    staticPaths: i18n.languages,
  } as const;
}

翻譯頁面

在頁面或 meta 檔案的檔名中加入語系代碼,即可翻譯該檔案:

meta.json
meta.cn.json
get-started.mdx
get-started.cn.mdx

沒有翻譯的頁面會改用預設語言顯示。若想改為依語言將檔案分別放在不同資料夾中,請參閱 i18n 路由。

Fumadocs 的版面配置會自動在連結中加入語系。

在您自己的元件中,請從路徑讀取語系:

'use client';
import { Link, useRouter } from 'waku/router/client';

export function AboutLink() {
  const lang = useRouter().path.split('/')[1];

  return <Link to={`/${lang}/about`}>About</Link>;
}

內建搜尋無須額外設定即可為所有語言建立索引,預設的搜尋對話方塊則會搜尋目前語系的內容。

How is this guide?

最後更新於