Next.js國際化全面指南
Next.js作為一個流行的React框架,為構建多語言支持的應用程序提供了強大的支持。本指南將引導你完成在Next.js項目中實現國際化(i18n)的步驟。我們將涵蓋路由設置、本地化處理和翻譯內容管理。
理解國際化術語
區域設置(Locale)
區域設置是一組語言和格式化偏好的標識符。它包括用戶的首選語言,也可能指示他們的地理區域。例如:
- 'en-US':美國使用的英語
- 'nl-NL':荷蘭使用的荷蘭語
- 'en':沒有特定區域的英語
設置Next.js國際化
創建新的Next.js應用
如果你還沒有,使用以下命令創建一個新的Next.js項目:
$ npx create-next-app@latest my-i18n-app
設置國際化路由
為用戶提供無縫體驗,根據他們的首選語言調整你的應用程序至關重要。這可以通過調整路由機制來實現。
利用用戶的語言偏好
通過使用像@formatjs/intl-localematcher
和negotiator
這樣的庫,你可以根據用戶的headers和你支持的區域設置來確定用戶的首選區域設置。這有助于確保用戶被導向到你網站的正確語言版本。
$ npm install @formatjs/intl-localematcher negotiator
實現基于區域設置的路由
Next.js允許你通過子路徑(/fr/products)
或域名(my-site.fr/products)
來國際化路由。這些信息使你能夠在中間件中根據用戶的首選區域設置重定向用戶。
在src/
目錄下創建middleware.ts
文件:
// middleware.ts
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { NextRequest, NextResponse } from 'next/server'
let defaultLocale = 'en'
let locales = ['cn', 'de', 'en']
// 獲取首選區域設置,類似上面或使用庫
function getLocale(request: NextRequest) {
const acceptedLanguage = request.headers.get('accept-language') ?? undefined
let headers = { 'accept-language': acceptedLanguage }
let languages = new Negotiator({ headers }).languages()
return match(languages, locales, defaultLocale) // -> 'en-US'
}
export function middleware(request: NextRequest) {
// 檢查路徑中是否有任何支持的區域設置
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// 如果沒有區域設置則重定向
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
// 例如,傳入的請求是/products
// 新的URL現在是/en-US/products
return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url))
}
}
export const config = {
matcher: [
// 跳過所有內部路徑 (_next, assets, api)
'/((?!api|assets|.*\\..*|_next).*)',
// 可選:只在根 (/) URL 上運行
// '/'
],
}
組織文件以進行基于區域設置的處理
為了使Next.js能夠在路由中動態管理不同的區域設置,將所有特殊文件嵌套在app/[lang]
中。
例如:
// app/[lang]/page.tsx
export default async function Page({ params: { lang } }) {
return ...
}
實現本地化
本地化涉及根據用戶的首選區域設置調整顯示的內容。這可以通過為每種支持的語言維護單獨的字典來實現。
創建字典
例如,我們考慮Next.js主頁的英語、荷蘭語和中文翻譯:
app/[lang]/dictionaries
dictionaries/en.json
:
{
"get_started": "Get started by editing",
"doc": "Find in-depth information about Next.js features and API.",
"learn": "Learn about Next.js in an interactive course with quizzes!",
"template": "Explore the Next.js 13 playground.",
"deploy": "Instantly deploy your Next.js site to a shareable URL with Vercel."
}
dictionaries/de.json:
{
"get_started": "Beginnen Sie, indem Sie bearbeiten",
"doc": "Finden Sie ausführliche Informationen zu den Funktionen und der API von Next.js.",
"learn": "Erfahren Sie mehr über Next.js in einem interaktiven Kurs mit Quizfragen!",
"template": "Erkunden Sie den Next.js 13-Spielplatz.",
"deploy": "Bereiten Sie Ihre Next.js-Website sofort für die Bereitstellung auf einer gemeinsam nutzbaren URL mit Vercel vor."
}
dictionaries/cn.json:
{
"get_started": "通過編輯開始",
"doc": "查找關于 Next.js 功能和 API 的深入信息。",
"learn": "通過互動課程學習 Next.js,包括測驗!",
"template": "探索 Next.js 13 的示范環境。",
"deploy": "使用 Vercel 立即部署您的 Next.js 網站到可共享的 URL。"
}
加載翻譯
創建一個getDictionary函數來加載請求的區域設置的翻譯。
import 'server-only'
export type Locale = keyof typeof dictionaries
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
de: () => import('./dictionaries/de.json').then((module) => module.default),
cn: () => import('./dictionaries/cn.json').then((module) => module.default),
}
export const getDictionary = async (locale: Locale) => dictionaries[locale]()
在組件中使用翻譯
現在你可以在布局或頁面中獲取字典以顯示翻譯后的內容。
import SwitchLang from '@/components/SwitchLang/SwitchLang'
import Image from 'next/image'
import { Locale, getDictionary } from './dictionaries'
import styles from './page.module.css'
type Props = {
params: {
lang: Locale
}
}
export default async function Home({ params: { lang } }: Props) {
const intl = await getDictionary(lang)
return (
<main className={styles.main}>
<div className={styles.description}>
<p>
{intl.get_started}
<code className={styles.code}>src/app/page.tsx</code>
</p>
<SwitchLang />
{/* ... 其余代碼 ... */}
</div>
{/* ... 其余代碼 ... */}
<div className={styles.grid}>
<a
className={styles.card}
target="_blank"
rel="noopener noreferrer"
>
<h2>
Docs <span>-></span>
</h2>
<p>{intl.doc}</p>
</a>
{/* ... 其他卡片 ... */}
</div>
</main>
)
}
為多個區域設置進行靜態生成
要為一組區域設置生成靜態路由,在任何頁面或布局中使用generateStaticParams。這可以全局設置,例如在根布局中:
// app/[lang]/layout.ts
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'de' }, { lang: 'cn' }]
}
export default function Root({ children, params }) {
return (
<html lang={params.lang}>
<body>{children}</body>
</html>
)
}
結論
在Next.js中實現國際化為來自不同語言背景的用戶提供了無縫體驗。通過調整路由,你可以為全球用戶創建更加包容和易于訪問的應用程序。