Skip to Content
🎉 Nextra 4.0 已发布。dimaMachina 正在 寻找新工作或咨询机会 
文档指南Next.js I18n

Next.js I18n

Warning

此功能仅在 nextra-theme-docs 中可用。

Nextra 开箱即用地支持 Next.js 国际化路由 。 本文档解释了如何配置和使用它。

添加 i18n 配置

要为您的 Nextra 应用添加多语言页面,您需要首先在 next.config.mjs 中配置 i18n

next.config.mjs
import nextra from 'nextra' const withNextra = nextra({ // ... other Nextra config options }) export default withNextra({ i18n: { locales: ['en', 'zh', 'de'], defaultLocale: 'en' } })
Note

您可以在 next.config 文件中使用任何格式的 UTS 区域设置标识符  来定义您的 locales,例如语言与区域 格式 en-US(美国英语)。

配置文档主题

i18n 选项添加到您的 theme.config.jsx 以配置语言 下拉菜单:

theme.config.jsx
i18n: [ { locale: 'en', name: 'English' }, { locale: 'zh', name: '中文' }, { locale: 'de', name: 'Deutsch' }, { locale: 'ar', name: 'العربية', direction: 'rtl' } ]

自动检测并重定向到用户选择的语言 (optional)

您可以自动检测用户的首选语言并将他们重定向到 站点的相应版本。要实现此功能,请在项目根目录创建一个 middleware.tsmiddleware.js 文件,并从中导出 Nextra 的 中间件函数,该函数来自 nextra/locales

middleware.ts
export { middleware } from 'nextra/locales' export const config = { // Matcher ignoring `/_next/` and `/api/` matcher: [ '/((?!api|_next/static|_next/image|favicon.ico|icon.svg|apple-icon.png|manifest|_pagefind).*)' ] }
Warning

此方法对于使用 nextConfig 中的 output: 'export' 静态导出的 i18n 站点无效。

自定义 404 页面 (optional)

您可以为使用共享主题布局的 i18n 网站创建一个带有翻译的自定义 not-found.jsx。要获取实现此功能的指导,您可以查看 SWR i18n 示例 

Last updated on