Fumadocs

国际化

在文档中支持多种语言

定义配置

Fumadocs core 提供了 i18n 支持所需的必要中间件和选项。

您可以定义一个配置,在实用工具之间共享。

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

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

隐藏语言环境前缀

要隐藏语言环境前缀(例如 /en/page -> /page),请使用 hideLocale 选项。

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

export const i18n = defineI18n({
  defaultLanguage: 'en',
  languages: ['en', 'cn'],
  hideLocale: 'default-locale',
});
模式描述
always始终隐藏前缀,从 cookie 检测语言环境
default-locale仅隐藏默认语言环境
never永不隐藏前缀(默认)

使用 always

always 模式下,语言环境会作为 cookie 存储(由中间件设置),这对于静态站点来说不是最优选择。

这可能会导致不希望的缓存问题,并且需要在 SEO 上额外注意,以确保搜索引擎能够正确索引您的页面。

回退语言

当页面缺少翻译时使用的回退语言,默认使用您的 defaultLanguage

支持:

  • languages 数组中的一种语言。
  • 当设置为 null 时,不会使用回退。
import { defineI18n } from 'fumadocs-core/i18n';

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

中间件

将用户重定向到合适的语言环境,它可以从 i18n.ts 中自定义。

middleware.ts
import { createI18nMiddleware } from 'fumadocs-core/i18n/middleware';
import { i18n } from '@/lib/i18n';

export default createI18nMiddleware(i18n);

export const config = {
  // Matcher ignoring `/_next/` and `/api/`
  // You may need to adjust it to ignore static assets in `/public` folder
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

当启用 hideLocale 时,它使用 NextResponse.rewrite 来隐藏语言环境前缀。

How is this guide?

Last updated on