如何在使用 App Router 的 Next.js 應用程式中實現國際化
讓您的 React 應用程式更具可及性,並透過國際化(i18n)開拓新市場。
隨著世界日益全球化,對於網頁開發者來說,建構能夠滿足來自不同國家和文化使用者需求的應用程式變得越來越重要。實現這一目標的關鍵方法之一是透過國際化(i18n),它讓您能夠將應用程式調整為不同的語言、貨幣和日期格式。
在本文中,我們將探討如何為您的 React Next.js 應用程式添加具備伺服器端渲染的國際化功能。 TL;DR: 完整範例請見此處。
本指南適用於使用 App Router 的 Next.js 應用程式。
如果您使用的是 Pages Router,請參閱此指南。
步驟 1: 安裝一個 i18n 函式庫
要在您的 Next.js 應用程式中實現國際化,我們首先會選擇一個 i18n 函式庫。有幾個受歡迎的函式庫,其中包括 next-intl。不過在這個範例中,我們將使用 TacoTranslate。
TacoTranslate 使用先進的 AI 自動將您的字串翻譯成任何語言,讓您擺脫繁瑣的 JSON 檔案管理。
讓我們在終端機使用 npm 安裝它:
npm install tacotranslate
步驟 2: 創建一個免費的 TacoTranslate 帳戶
現在您已經安裝了模組,接下來是建立您的 TacoTranslate 帳戶、翻譯專案及相關的 API 金鑰。在這裡建立帳戶。 它是免費的,且不需要您提供信用卡資訊。
在 TacoTranslate 應用程式的使用者介面中,建立一個專案,並導航到其 API 金鑰標籤頁。建立一個 read
金鑰和一個 read/write
金鑰。我們將把它們儲存為環境變數。 read
金鑰即所謂的 public
,而 read/write
金鑰則是 secret
。例如,你可以將它們新增到專案根目錄的 .env
檔案中。
TACOTRANSLATE_PUBLIC_API_KEY=123456
TACOTRANSLATE_SECRET_API_KEY=789010
務必切勿將秘密 read/write
API 密鑰洩露給客戶端生產環境。
我們還將添加另外兩個環境變數:TACOTRANSLATE_DEFAULT_LOCALE
和 TACOTRANSLATE_ORIGIN
。
TACOTRANSLATE_DEFAULT_LOCALE
:預設的備援語系代碼。在此範例中,我們將其設為en
,代表英文。TACOTRANSLATE_ORIGIN
:字串儲存的「資料夾」,例如您的網站 URL。在此閱讀關於 origins 的更多資訊。
TACOTRANSLATE_DEFAULT_LOCALE=en
TACOTRANSLATE_ORIGIN=your-website-url.com
步驟 3: 設定 TacoTranslate
要將 TacoTranslate 整合到您的應用程式中,您需要使用先前的 API 金鑰來建立一個客戶端。例如,建立一個名為 /tacotranslate-client.js
的檔案。
const {default: createTacoTranslateClient} = require('tacotranslate');
const tacoTranslate = createTacoTranslateClient({
apiKey:
process.env.TACOTRANSLATE_SECRET_API_KEY ??
process.env.TACOTRANSLATE_PUBLIC_API_KEY ??
process.env.TACOTRANSLATE_API_KEY,
projectLocale:
process.env.TACOTRANSLATE_IS_PRODUCTION === 'true'
? process.env.TACOTRANSLATE_PROJECT_LOCALE
: undefined,
});
module.exports = tacoTranslate;
我們將很快自動定義 TACOTRANSLATE_API_KEY
和 TACOTRANSLATE_PROJECT_LOCALE
。
將客戶端創建放在單獨的檔案中,方便日後再次使用。getLocales
只是一個帶有內建錯誤處理的工具函式。現在,建立一個名為 /app/[locale]/tacotranslate.tsx
的檔案,我們將在其中實作 TacoTranslate
提供者。
'use client';
import React, {type ReactNode} from 'react';
import {
type TranslationContextProperties,
TacoTranslate as ImportedTacoTranslate,
} from 'tacotranslate/react';
import tacoTranslateClient from '@/tacotranslate-client';
export default function TacoTranslate({
locale,
origin,
localizations,
children,
}: TranslationContextProperties & {
readonly children: ReactNode;
}) {
return (
<ImportedTacoTranslate
client={tacoTranslateClient}
locale={locale}
origin={origin}
localizations={localizations}
>
{children}
</ImportedTacoTranslate>
);
}
請注意 'use client';
,這表示這是一個客戶端組件。
現在上下文提供者已經準備好,請建立一個名為 /app/[locale]/layout.tsx
的檔案,這是我們應用程式中的根佈局。請注意,此路徑中的資料夾使用了 Dynamic Routes,其中 [locale]
是動態參數。
import React, {type ReactNode} from 'react';
import {type Locale, isRightToLeftLocaleCode} from 'tacotranslate';
import './global.css';
import tacoTranslateClient from '@/tacotranslate-client';
import TacoTranslate from './tacotranslate';
export async function generateStaticParams() {
const locales = await tacoTranslateClient.getLocales();
return locales.map((locale) => ({locale}));
}
type RootLayoutParameters = {
readonly params: Promise<{locale: Locale}>;
readonly children: ReactNode;
};
export default async function RootLayout({params, children}: RootLayoutParameters) {
const {locale} = await params;
const origin = process.env.TACOTRANSLATE_ORIGIN;
const localizations = await tacoTranslateClient.getLocalizations({
locale,
origins: [origin /* , other origins to fetch */],
});
return (
<html lang={locale} dir={isRightToLeftLocaleCode(locale) ? 'rtl' : 'ltr'}>
<body>
<TacoTranslate
locale={locale}
origin={origin}
localizations={localizations}
>
{children}
</TacoTranslate>
</body>
</html>
);
}
這裡首先要注意的是,我們使用了 Dynamic Route
參數 [locale]
來抓取該語言的翻譯。此外,generateStaticParams
確保了你項目中啟用的所有語言代碼都被預先渲染。
現在,讓我們來建立第一個頁面吧!建立一個名為 /app/[locale]/page.tsx
的檔案。
import React from 'react';
import {Translate} from 'tacotranslate/react';
export const revalidate = 60;
export default async function Page() {
return (
<Translate string="Hello, world!" />
);
}
請注意 revalidate
變數,它告訴 Next.js 在 60 秒後重新建置頁面,並保持您的翻譯為最新狀態。
步驟 4: 實現伺服器端渲染
TacoTranslate 支援伺服器端渲染。這大幅提升了使用者體驗,能立即顯示已翻譯的內容,而不是先閃現未翻譯的內容。此外,我們可以跳過客戶端的網路請求,因為我們已經擁有用戶正在瀏覽頁面的所需翻譯內容。
要設定伺服器端渲染,請建立或修改 /next.config.js
:
const withTacoTranslate = require('tacotranslate/next/config').default;
const tacoTranslateClient = require('./tacotranslate-client');
module.exports = async () => {
const config = await withTacoTranslate(
{},
{
client: tacoTranslateClient,
isProduction:
process.env.TACOTRANSLATE_ENV === 'production' ||
process.env.VERCEL_ENV === 'production' ||
(!(process.env.TACOTRANSLATE_ENV || process.env.VERCEL_ENV) &&
process.env.NODE_ENV === 'production'),
}
);
// NOTE: Remove i18n from config when using the app router
return {...config, i18n: undefined};
};
修改 isProduction
檢查以適合您的設置。如果 true
,TacoTranslate 將顯示公有 API 金鑰。如果我們在本地、測試或暫存環境 (isProduction
is false
) 中,我們將使用密鑰 read/write
API 金鑰來確保發送新字串進行翻譯。
為了確保路由和重定向如預期運作,我們需要建立一個名為 /middleware.ts
的檔案。透過使用 Middleware,我們可以將使用者重定向到以其偏好語言顯示的頁面。
import {type NextRequest} from 'next/server';
import {middleware as tacoTranslateMiddleware} from 'tacotranslate/next';
import tacoTranslate from '@/tacotranslate-client';
export const config = {
matcher: ['/((?!api|_next|favicon.ico).*)'],
};
export async function middleware(request: NextRequest) {
return tacoTranslateMiddleware(tacoTranslate, request);
}
請確保根據Next.js Middleware 文件設定 matcher
。
在客戶端,你可以更改 locale
cookie 來改變使用者偏好的語言。請參考 完整範例程式碼,獲取如何操作的靈感!
步驟 5: 部署並測試!
我們完成了!當你將任何字串加入到 Translate
元件時,你的 React 應用程式現在會自動進行翻譯。請注意,只有擁有 read/write
權限的 API 金鑰環境,才能新增要翻譯的字串。我們建議設置一個封閉且安全的暫存環境,在那裡你可以使用這樣的 API 金鑰測試你的正式應用程式,並在上線前新增新的字串。這樣可以防止任何人竊取你的秘密 API 金鑰,並避免因新增毫無關聯的字串而使翻譯專案膨脹。
Be sure to check out the complete example over at our GitHub profile. There, you’ll also find an example of how to do this using the Pages Router! If you encounter any problems, feel free to reach out, and we’ll be more than happy to help.
TacoTranslate lets you automatically localize your React applications quickly to and from over 75 languages. Get started today!