国际化
通过国际化路由和本地化内容,添加对多种语言的支持。
Next.js 允许你配置路由和内容渲染以支持多种语言。让你的站点适应不同的 locale 包括翻译内容(本地化)和国际化路由。
术语
- Locale: 一组语言和格式偏好的标识符。这通常包括用户的首选语言,可能还包括其地理区域。
en-US:美国所说的英语nl-NL:荷兰所说的荷兰语nl:荷兰语,无特定地区
路由概览
建议使用浏览器中用户的语言偏好来选择要使用的 locale。更改首选语言会修改传入你应用的 Accept-Language 标头。
例如,使用以下库,你可以查看传入的 Request,根据 Headers、你计划支持的 locale 以及默认 locale 来确定要选择哪个 locale。
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
let headers = { 'accept-language': 'en-US,en;q=0.5' }
let languages = new Negotiator({ headers }).languages()
let locales = ['en-US', 'nl-NL', 'nl']
let defaultLocale = 'en-US'
match(languages, locales, defaultLocale) // -> 'en-US'
路由可以通过子路径(/fr/products)或域名(my-site.fr/products)实现国际化。有了这些信息,你现在就可以在 Proxy 中根据 locale 重定向用户。
import { NextResponse } from "next/server";
let locales = ['en-US', 'nl-NL', 'nl']
// Get the preferred locale, similar to the above or using a library
function getLocale(request) { ... }
export function proxy(request) {
// Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) return
// Redirect if there is no locale
const locale = getLocale(request)
request.nextUrl.pathname = `/${locale}${pathname}`
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(request.nextUrl)
}
export const config = {
matcher: [
// Skip all internal paths (_next)
'/((?!_next).*)',
// Optional: only run on root (/) URL
// '/'
],
}
最后,确保 app/ 内的所有特殊文件都嵌套在 app/[lang] 下。这使 Next.js 路由器能够动态处理路由中的不同 locale,并将 lang 参数转发到每个布局和页面。例如:
TypeScript
// You now have access to the current locale
// e.g. /en-US/products -> `lang` is "en-US"
export default async function Page({ params }: PageProps<'/[lang]'>) {
const { lang } = await params
return ...
}
JavaScript
// You now have access to the current locale
// e.g. /en-US/products -> `lang` is "en-US"
export default async function Page({ params }) {
const { lang } = await params
return ...
}
须知:
PageProps和LayoutProps是全局可用的 TypeScript 辅助类型,为路由参数提供强类型。更多细节请参阅 PageProps 和 LayoutProps。
根布局也可以嵌套在新文件夹中(例如 app/[lang]/layout.js)。
本地化
根据用户的首选 locale(即本地化)更改显示的内容,并不是 Next.js 特有的功能。下面描述的模式在任何 Web 应用中同样适用。
假设我们想在应用中同时支持英语和荷兰语内容。我们可能会维护两个不同的“字典”,这些对象提供了从某个键到本地化字符串的映射。例如:
{
"products": {
"cart": "Add to Cart"
}
}
{
"products": {
"cart": "Toevoegen aan Winkelwagen"
}
}
然后我们可以创建一个 getDictionary 函数,用于加载所请求 locale 的翻译:
TypeScript
import 'server-only'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export type Locale = keyof typeof dictionaries
export const hasLocale = (locale: string): locale is Locale =>
locale in dictionaries
export const getDictionary = async (locale: Locale) => dictionaries[locale]()
JavaScript
import 'server-only'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export const hasLocale = (locale) => locale in dictionaries
export const getDictionary = async (locale) => dictionaries[locale]()
给定当前选定的语言,我们可以在布局或页面内部获取字典。
由于 lang 的类型为 string,使用 hasLocale 可以将类型收窄为你支持的语言环境。对不受支持的语言环境调用 notFound() 会渲染 not-found UI。
TypeScript
import { notFound } from 'next/navigation'
import { getDictionary, hasLocale } from './dictionaries'
export default async function Page({ params }: PageProps<'/[lang]'>) {
const { lang } = await params
if (!hasLocale(lang)) notFound()
const dict = await getDictionary(lang)
return <button>{dict.products.cart}</button> // Add to Cart
}
JavaScript
import { notFound } from 'next/navigation'
import { getDictionary, hasLocale } from './dictionaries'
export default async function Page({ params }) {
const { lang } = await params
if (!hasLocale(lang)) notFound()
const dict = await getDictionary(lang)
return <button>{dict.products.cart}</button> // Add to Cart
}
由于 app/ 目录中的所有布局和页面默认都是服务器组件,我们无需担心翻译文件的大小会影响客户端 JavaScript 包体积。这段代码只会在服务器上运行,并且只有生成的 HTML 会被发送到浏览器。
在整个应用中共享语言环境
语言环境常常在接收它的页面之外也需要用到,例如在共享的数据获取工具函数或深层嵌套的组件中。与其逐层通过 prop 传递 lang,我们可以直接使用 next/root-params 读取它。
next/root-params 会为根布局之上的每个动态段导出一个 getter。由于每条路由都嵌套在 app/[lang] 下,lang 是一个根参数,任何服务器组件或服务端工具函数都可以调用它的 getter。我们可以把语言环境的查找移到 getDictionary 中,这样调用方不再需要传入 lang:
TypeScript
import { lang } from 'next/root-params'
import { notFound } from 'next/navigation'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export type Locale = keyof typeof dictionaries
export const hasLocale = (locale: string): locale is Locale =>
locale in dictionaries
export const getDictionary = async () => {
const locale = await lang()
if (!hasLocale(locale)) notFound()
return dictionaries[locale]()
}
JavaScript
import { lang } from 'next/root-params'
import { notFound } from 'next/navigation'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export const hasLocale = (locale) => locale in dictionaries
export const getDictionary = async () => {
const locale = await lang()
if (!hasLocale(locale)) notFound()
return dictionaries[locale]()
}
须知:
从
next/root-params导入的文件不需要import 'server-only'。如果在客户端组件中使用,该导入在构建时就会失败。
随后页面和组件调用 getDictionary() 时无需传参,因为语言环境会在内部解析:
TypeScript
import { getDictionary } from './dictionaries'
export default async function Page() {
const dict = await getDictionary()
return <button>{dict.products.cart}</button> // Add to Cart
}
JavaScript
import { getDictionary } from './dictionaries'
export default async function Page() {
const dict = await getDictionary()
return <button>{dict.products.cart}</button> // Add to Cart
}
须知:
根参数 getter 会在服务器组件和服务端工具函数中运行,但不会在客户端组件、服务器操作或路由处理器中运行。完整的 API 及其缓存行为请参见
next/root-params。
静态渲染
要为给定的一组语言环境生成静态路由,我们可以在任意页面或布局中使用 generateStaticParams。这可以是全局的,例如在根布局中:
TypeScript
export async function generateStaticParams() {
return [{ lang: 'en-US' }, { lang: 'de' }]
}
export default async function RootLayout({
children,
params,
}: LayoutProps<'/[lang]'>) {
return (
<html lang={(await params).lang}>
<body>{children}</body>
</html>
)
}
JavaScript
export async function generateStaticParams() {
return [{ lang: 'en-US' }, { lang: 'de' }]
}
export default async function RootLayout({ children, params }) {
return (
<html lang={(await params).lang}>
<body>{children}</body>
</html>
)
}
资源
- 最简 i18n 路由与翻译
next-intlnext-internationalnext-i18n-routerparaglide-nextlinguitolgeenext-intlayergt-next
相关 API 参考与约定。
- root-params:next/root-params 模块的 API 参考,该模块提供对根级路由参数的访问。