NNext.js 中文网 GitHub

国际化

通过国际化路由和本地化内容添加对多种语言的支持。

Next.js 使你能够配置内容的路由和渲染,以支持多种语言。让你的站点适配不同的区域设置(locale)包括翻译内容(本地化)和国际化路由。

术语#

  • Locale(区域设置): 一组语言和格式偏好的标识符。通常包括用户的首选语言,可能还包括其地理区域。
    • en-US:美国使用的英语
    • nl-NL:荷兰使用的荷兰语
    • nl:荷兰语,无特定区域

路由概述#

建议使用浏览器中的用户语言偏好来选择要使用的区域设置。更改首选语言会修改发送到你的应用程序的 Accept-Language 请求头。

例如,使用以下库,你可以根据 Headers、计划支持的区域设置以及默认区域设置,查看传入的 Request 来确定选择哪个区域设置。

proxy.js
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 中根据区域设置重定向用户。

proxy.js
import { NextResponse } from "next/server";

let locales = ['en-US', 'nl-NL', 'nl']

// 获取首选区域设置,方法类似上文或使用某个库
function getLocale(request) { ... }

export function proxy(request) {
  // 检查路径名中是否存在受支持的区域设置
  const { pathname } = request.nextUrl
  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  )

  if (pathnameHasLocale) return

  // 如果没有区域设置则重定向
  const locale = getLocale(request)
  request.nextUrl.pathname = `/${locale}${pathname}`
  // 例如传入的请求是 /products
  // 新的 URL 现在是 /en-US/products
  return NextResponse.redirect(request.nextUrl)
}

export const config = {
  matcher: [
    // 跳过所有内部路径 (_next)
    '/((?!_next).*)',
    // 可选:仅在根 (/) URL 上运行
    // '/'
  ],
}

最后,确保 app/ 中的所有特殊文件都嵌套在 app/[lang] 下。这使 Next.js 路由器能够动态处理路由中的不同区域设置,并将 lang 参数转发给每个布局和页面。例如:

app/[lang]/page.tsx
// 你现在可以访问当前的区域设置
// 例如 /en-US/products -> `lang` 为 "en-US"
export default async function Page({ params }: PageProps<'/[lang]'>) {
  const { lang } = await params
  return ...
}
app/[lang]/page.js
// 你现在可以访问当前的区域设置
// 例如 /en-US/products -> `lang` 为 "en-US"
export default async function Page({ params }) {
  const { lang } = await params
  return ...
}

小知识: PageProps 和 LayoutProps 是全局可用的 TypeScript 辅助类型,为路由参数提供强类型。有关更多详情,请参阅 PageProps 和 LayoutProps。

根布局也可以嵌套在新文件夹中(例如 app/[lang]/layout.js)。

本地化#

根据用户首选的区域设置更改显示的内容,即本地化,并不是 Next.js 特有的功能。下面描述的模式对任何 Web 应用程序都同样适用。

假设我们希望在应用程序中同时支持英语和荷兰语内容。我们可以维护两个不同的"词典"(dictionary),即把某个键映射到本地化字符串的对象。例如:

dictionaries/en.json
{
  "products": {
    "cart": "Add to Cart"
  }
}
dictionaries/nl.json
{
  "products": {
    "cart": "Toevoegen aan Winkelwagen"
  }
}

然后我们可以创建一个 getDictionary 函数来加载所请求区域设置的翻译:

app/[lang]/dictionaries.ts
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]()
app/[lang]/dictionaries.js
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。

app/[lang]/page.tsx
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> // 添加到购物车
}
app/[lang]/page.js
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> // 添加到购物车
}

由于 app/ 目录中的所有布局和页面默认都是 Server Components,我们无需担心翻译文件的大小会影响客户端 JavaScript 包的大小。这段代码只在服务端运行,只有生成的 HTML 会被发送到浏览器。

在应用中共享区域设置#

区域设置通常不仅在接收它的页面中使用,还会在共享的数据获取工具函数或深层嵌套的组件中需要。与其通过每一层逐级传递 lang 属性(prop drilling),我们可以使用 next/root-params 直接读取它。

next/root-params 为根布局之上的每个动态段导出一个 getter。由于每个路由都嵌套在 app/[lang] 下,lang 是一个根参数,任何 Server Component 或服务端工具函数都可以调用它的 getter。我们可以把区域设置的查找移入 getDictionary,这样调用方就不再需要传递 lang:

app/[lang]/dictionaries.ts
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]()
}
app/[lang]/dictionaries.js
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'。如果在 Client Component 中使用,该导入会在构建时直接失败。

随后,页面和组件可以调用不带参数的 getDictionary(),因为区域设置已在内部解析:

app/[lang]/page.tsx
import { getDictionary } from './dictionaries'

export default async function Page() {
  const dict = await getDictionary()
  return <button>{dict.products.cart}</button> // 添加到购物车
}
app/[lang]/page.js
import { getDictionary } from './dictionaries'

export default async function Page() {
  const dict = await getDictionary()
  return <button>{dict.products.cart}</button> // 添加到购物车
}

小知识: 根参数 getter 可在 Server Components 和服务端工具函数中运行,但不能在 Client Components、Server Actions 或 Route Handlers 中运行。有关完整 API 及其缓存行为,请参阅 next/root-params。

静态渲染#

要为给定的一组区域设置生成静态路由,我们可以在任意页面或布局中使用 generateStaticParams。这可以是全局的,例如在根布局中:

app/[lang]/layout.tsx
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>
  )
}
app/[lang]/layout.js
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>
  )
}

资源#

Next.js 中文网