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 应用程序的用户界面中,创建一个项目,然后导航到其 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 中间件文档设置 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!

来自 Nattskiftet 的产品挪威制造