国际化
在 Next.js 中, 你可以通过配置内容的路由和渲染来支持多种语言. 使你的网站适应不同的语言环境包括翻译内容(本地化)和国际化路由.
Terminology (术语)
- Locale(地区): 一组语言和语言格式化中的标识符, 通常包括用户的首选语言以及可能的地理区域.
en-US
: 美国的英文nl-NL
: 荷兰的荷兰语nl
: 未指定地区的荷兰语
Routing Overview (路由简介)
建议使用浏览器中的用户语言首选项来选择要使用哪种语言. 更改首选语言将修改传入应用程序的 Accept-Language
头.
比如, 使用下列库, 你可以通过查看到来的 Request
对象, 基于 Headers
头, 计划支持的本地语言, 默认本地语言, 来决定选择哪个地区.
middleware.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
)进行国际化. 有了这些信息, 你现在就可以根据 Middleware(中间件) 内的地域对用户进行重定向.
middleware.js
let locales = ['en-US', 'nl-NL', 'nl']
// Get the preferred locale, similar to the above or using a library
function getLocale(request) { ... }
export function middleware(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 Response.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
参数传递给每一 page(页) 和每一个 layout(布局). 比如:
app/[lang]/page.js
// You now have access to the current locale
// e.g. /en-US/products -> `lang` is "en-US"
export default async function Page({ params: { lang } }) {
return ...
}
根布局也可以被嵌套在一个新的文件夹中(如, app/[lang]/layout.js
).