跳到内容

国际化

Next.js 允许您配置内容的路由和渲染以支持多种语言。让您的网站适应不同的区域设置包括翻译内容(本地化)和国际化路由。

术语

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

路由概述

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

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

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']
 
// 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 路由器能够动态处理路由中的不同区域设置,并将 `lang` 参数转发给每个布局和页面。例如:

app/[lang]/page.tsx
// You now have access to the current locale
// e.g. /en-US/products -> `lang` is "en-US"
export default async function Page({
  params,
}: {
  params: Promise<{ lang: string }>
}) {
  const { lang } = await params
  return ...
}

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

本地化

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

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

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 const getDictionary = async (locale: 'en' | 'nl') =>
  dictionaries[locale]()

给定当前选择的语言,我们可以在布局或页面中获取字典。

app/[lang]/page.tsx
import { getDictionary } from './dictionaries'
 
export default async function Page({
  params,
}: {
  params: Promise<{ lang: 'en' | 'nl' }>
}) {
  const { lang } = await params
  const dict = await getDictionary(lang) // en
  return <button>{dict.products.cart}</button> // Add to Cart
}

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

静态渲染

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

app/[lang]/layout.tsx
export async function generateStaticParams() {
  return [{ lang: 'en-US' }, { lang: 'de' }]
}
 
export default async function RootLayout({
  children,
  params,
}: Readonly<{
  children: React.ReactNode
  params: Promise<{ lang: 'en-US' | 'de' }>
}>) {
  return (
    <html lang={(await params).lang}>
      <body>{children}</body>
    </html>
  )
}

资源