TacoTranslate
/
文件定價
 
教學
5月04日

如何在使用 App Router 的 Next.js 應用程式中實作國際化

透過國際化 (i18n),讓你的 React 應用程式更具無障礙性並開拓新市場。

隨著世界日益全球化,網頁開發者建立能夠迎合不同國家和文化使用者的應用程式變得愈加重要。實現這一目標的關鍵方法之一是採用國際化(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 應用程式的 UI 中,建立一個專案,然後前往其 API 金鑰分頁。建立一個 read 金鑰,以及一個 read/write 金鑰。我們會將它們儲存為環境變數。read 金鑰就是我們所稱的 public,而 read/write 金鑰則是 secret。例如,您可以將它們新增到專案根目錄下的 .env 檔案中。

.env
TACOTRANSLATE_PUBLIC_API_KEY=123456
TACOTRANSLATE_SECRET_API_KEY=789010

務必不要將秘密 read/write API 金鑰洩露到客戶端的生產環境。

我們還會新增另外兩個環境變數:TACOTRANSLATE_DEFAULT_LOCALETACOTRANSLATE_ORIGIN

  • TACOTRANSLATE_DEFAULT_LOCALE: 預設的回退語系代碼。在此範例中,我們會將它設定為 en(英文)。
  • TACOTRANSLATE_ORIGIN: 您字串會被儲存的「資料夾」,例如您網站的 URL。 在此閱讀有關 origins 的更多資訊。
.env
TACOTRANSLATE_DEFAULT_LOCALE=en
TACOTRANSLATE_ORIGIN=your-website-url.com

第 3 步: 設定 TacoTranslate

要將 TacoTranslate 整合到您的應用程式中,您需要使用先前提供的 API 金鑰來建立一個客戶端。舉例來說,建立一個名為 /tacotranslate-client.js 的檔案。

/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_KEYTACOTRANSLATE_PROJECT_LOCALE

將客戶端建立在獨立的檔案中可以讓日後更容易重複使用。 getLocales 是一個帶有內建錯誤處理的工具函式。現在,建立一個名為 /app/[locale]/tacotranslate.tsx 的檔案,在那裡我們會實作 TacoTranslate 提供者。

/app/[locale]/tacotranslate.tsx
'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] 為動態參數。

/app/[locale]/layout.tsx
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 的檔案。

/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:

/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,我們可以將使用者重新導向到以其偏好語言呈現的頁面。

/middleware.ts
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 應用程式現在會自動被翻譯。請注意,只有擁有 API 金鑰 read/write 權限的環境才能建立要翻譯的新字串。我們建議設置一個封閉且安全的暫存(staging)環境,在那裡使用此類型的 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!

來自 Nattskiftet 的產品挪威製造