Next.js 国际化
⚠️
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
你可以使用任何格式的 UTS 语言标识符
来定义你的语言环境,例如带地区的语言格式 en-US
(美式英语)。
配置文档主题
在你的 theme.config.jsx
中添加 i18n
选项来配置语言下拉菜单:
theme.config.jsx
i18n: [
{ locale: 'en', name: 'English' },
{ locale: 'zh', name: '中文' },
{ locale: 'de', name: 'Deutsch' },
{ locale: 'ar', name: 'العربية', direction: 'rtl' }
]
自动检测并重定向到用户选择的语言(可选)
你可以自动检测用户的首选语言并将其重定向到相应的网站版本。要实现这一点,
在项目根目录创建 middleware.ts
或 middleware.js
文件,并从 nextra/locales
导出 Nextra 的中间件函数:
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
对于使用 output: 'export'
进行静态导出的 i18n 站点,此方法将不起作用。
自定义 404 页面(可选)
你可以为使用共享主题布局的 i18n 网站创建带有翻译的自定义 not-found.jsx
。
有关实现指南,你可以查看 SWR i18n 示例 。
Last updated on