为全球用户构建 React 应用需要一套稳健的国际化(i18n)策略。react-i18next 是最受欢迎的 React 本地化库,它构建于久经考验的 i18next 框架之上。本指南将带您了解本地化 React 应用所需的一切——从初始设置到利用 AI 驱动的翻译实现生产级的自动化。
react-i18next 是 React 国际化的事实标准,受到全球数千个生产级应用的信赖。以下是开发者选择它的原因:
安装 react-i18next 和核心 i18next 库:
npm install react-i18next i18next这些热门插件通过自动语言检测和懒加载翻译来增强您的 i18next 设置:
# Language detector (auto-detects user language)
npm install i18next-browser-languagedetector
# HTTP backend (load translations from server)
npm install i18next-http-backend良好的项目结构能确保您在添加更多语言时,翻译内容依然易于维护:
src/
├── i18n/
│ └── i18n.ts ← i18next configuration
├── locales/
│ ├── en/
│ │ └── translation.json ← English (source)
│ ├── fr/
│ │ └── translation.json ← French
│ ├── de/
│ │ └── translation.json ← German
│ ├── ja/
│ │ └── translation.json ← Japanese
│ └── es/
│ └── translation.json ← Spanish
├── components/
├── App.tsx
└── index.tsxreact-i18next 使用嵌套的 JSON 文件进行翻译。键支持点符号、{{变量}} 插值以及内置的复数形式:
// locales/en/translation.json
{
"welcome": {
"title": "Welcome to our platform",
"greeting": "Hello, {{name}}!",
"description": "Explore features and get started."
},
"nav": {
"home": "Home",
"dashboard": "Dashboard",
"settings": "Settings",
"logout": "Log out"
},
"cart": {
"empty": "Your cart is empty",
"item_one": "{{count}} item in your cart",
"item_other": "{{count}} items in your cart",
"checkout": "Proceed to checkout"
}
}i18next 支持两种主要的翻译加载方式:HTTP 后端(懒加载)和捆绑资源。请根据应用需求进行选择。
按需从服务器的 JSON 文件加载翻译。这能保持初始包体积较小,非常适合拥有多种语言或大型翻译文件的应用:
// src/i18n/i18n.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import HttpBackend from "i18next-http-backend";
i18n
.use(HttpBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
supportedLngs: ["en", "fr", "de", "ja", "es"],
defaultNS: "translation",
interpolation: {
escapeValue: false, // React already escapes by default
},
backend: {
loadPath: "/locales/{{lng}}/{{ns}}.json",
},
detection: {
order: ["localStorage", "navigator", "htmlTag"],
caches: ["localStorage"],
},
});
export default i18n;将翻译直接导入到包中。最适合小型应用,或当您需要立即使用翻译而无需网络请求时:
// src/i18n/i18n.ts — Bundled approach (no HTTP backend)
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import en from "../locales/en/translation.json";
import fr from "../locales/fr/translation.json";
import de from "../locales/de/translation.json";
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
supportedLngs: ["en", "fr", "de"],
defaultNS: "translation",
interpolation: {
escapeValue: false,
},
resources: {
en: { translation: en },
fr: { translation: fr },
de: { translation: de },
},
});
export default i18n;在渲染任何组件之前,在应用的入口点导入 i18n 配置文件。这可确保在 UI 渲染前加载好翻译:
// src/index.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./i18n/i18n"; // Initialize i18next before rendering
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);react-i18next 提供了两种主要的 API 来翻译组件:用于程序化访问的 useTranslation Hook,以及用于 JSX 富文本的 Trans 组件。
useTranslation Hook 是在函数式组件中访问翻译的最常用方式。它提供 t() 函数,并在语言更改时自动重新渲染:
import { useTranslation } from "react-i18next";
function WelcomeBanner() {
const { t } = useTranslation();
return (
<div>
<h1>{t("welcome.title")}</h1>
<p>{t("welcome.greeting", { name: "Alice" })}</p>
<p>{t("welcome.description")}</p>
</div>
);
}当翻译内容包含 HTML 或 JSX 元素(如加粗、链接等)时,请使用 Trans 组件。它能在翻译中保留您的 React 组件树:
import { Trans } from "react-i18next";
function RichTextExample() {
return (
<p>
<Trans i18nKey="richText.welcome">
Welcome to <strong>our platform</strong>.
Visit your <a href="/dashboard">dashboard</a> to get started.
</Trans>
</p>
);
}
// In the translation file:
// "richText.welcome": "Welcome to <1>our platform</1>. Visit your <3>dashboard</3> to get started."i18next 根据每种语言的 ICU 复数规则自动处理复数形式。传入 count 参数,i18next 将选择正确的复数形式:
// In translation JSON:
// "cart.item_one": "{{count}} item in your cart"
// "cart.item_other": "{{count}} items in your cart"
import { useTranslation } from "react-i18next";
function CartSummary({ itemCount }: { itemCount: number }) {
const { t } = useTranslation();
return (
<p>{t("cart.item", { count: itemCount })}</p>
);
}
// itemCount=0 → "0 items in your cart"
// itemCount=1 → "1 item in your cart"
// itemCount=5 → "5 items in your cart"命名空间允许您按功能或领域将翻译拆分为独立的文件。这提高了可维护性并支持翻译包的懒加载:
// src/i18n/i18n.ts
i18n.init({
defaultNS: "common",
ns: ["common", "dashboard", "auth", "errors"],
backend: {
loadPath: "/locales/{{lng}}/{{ns}}.json",
},
});
// Usage in components:
import { useTranslation } from "react-i18next";
function DashboardPage() {
// Load specific namespace
const { t } = useTranslation("dashboard");
return <h1>{t("title")}</h1>;
}
function LoginForm() {
// Load multiple namespaces
const { t } = useTranslation(["auth", "common"]);
return (
<form>
<h2>{t("auth:login.title")}</h2>
<button>{t("common:submit")}</button>
</form>
);
}react-i18next 使语言切换变得无缝。调用 i18n.changeLanguage(),所有使用 useTranslation 的组件都会自动以新语言重新渲染:
import { useTranslation } from "react-i18next";
const LANGUAGES = [
{ code: "en", label: "English" },
{ code: "fr", label: "Français" },
{ code: "de", label: "Deutsch" },
{ code: "ja", label: "日本語" },
{ code: "es", label: "Español" },
];
function LanguageSwitcher() {
const { i18n } = useTranslation();
const changeLanguage = (lng: string) => {
i18n.changeLanguage(lng);
};
return (
<select
value={i18n.language}
onChange={(e) => changeLanguage(e.target.value)}
>
{LANGUAGES.map(({ code, label }) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
);
}react-i18next 与 React Suspense 集成,以优雅地处理异步翻译加载。使用 HTTP 后端时,Suspense 在获取翻译期间提供了简洁的加载状态:
import { Suspense } from "react";
import { useTranslation } from "react-i18next";
// i18next supports React Suspense for async translation loading
function App() {
return (
<Suspense fallback={<div>Loading translations...</div>}>
<MainContent />
</Suspense>
);
}
function MainContent() {
const { t, ready } = useTranslation();
// With Suspense, 'ready' is always true here
return <h1>{t("welcome.title")}</h1>;
}i18next 支持完整的 TypeScript 集成。通过扩展 i18next 模块,您可以获得所有翻译键的自动补全和编译时检查,从而防止拼写错误和翻译缺失:
// src/i18n/types.ts
import "i18next";
import translation from "../locales/en/translation.json";
declare module "i18next" {
interface CustomTypeOptions {
defaultNS: "translation";
resources: {
translation: typeof translation;
};
}
}
// Now t() calls are fully type-safe:
// t("welcome.title") ✅ Autocomplete works
// t("welcome.greeting") ✅ Valid key
// t("invalid.key") ❌ TypeScript error对于使用 App Router 的 Next.js 应用,您可以在服务端和客户端组件中使用 i18next。为服务端翻译创建一个独立的 i18next 实例,以避免在请求之间共享状态:
// next-i18next.config.js (Next.js App Router)
// For Next.js 13+ with App Router, use next-intl or i18next directly
// src/i18n/server.ts
import { createInstance } from "i18next";
import { initReactI18next } from "react-i18next/initReactI18next";
export async function getServerTranslation(lng: string) {
const i18nInstance = createInstance();
await i18nInstance.use(initReactI18next).init({
lng,
fallbackLng: "en",
resources: {
[lng]: {
translation: (await import(`../locales/${lng}/translation.json`)).default,
},
},
});
return i18nInstance;
}
// In a Server Component:
export default async function Page({ params }: { params: { lng: string } }) {
const i18n = await getServerTranslation(params.lng);
const t = i18n.t.bind(i18n);
return <h1>{t("welcome.title")}</h1>;
}设置好 react-i18next 只是成功了一半——您仍然需要为每种目标语言提供高质量的翻译。手动翻译数十个 JSON 文件既缓慢、昂贵又容易出错。AI 驱动的翻译改变了这一局面。
l10n.dev 是专为开发者本地化工作流构建的。它能原生理解您的 JSON 翻译文件,并生成听起来自然、而非机器生成的翻译:
ai-l10n npm 包将 AI 翻译直接集成到您的开发工作流中。通过命令行翻译您的 JSON 文件:
# Install the l10n.dev CLI
npm install ai-l10n
# Translate your JSON files to multiple languages at once
npx ai-l10n translate src/locales/en/translation.json \
--languages fr,de,ja,es,ko,zh-CN将翻译自动化添加到您的构建流水线,确保翻译始终保持最新:
{
"scripts": {
"translate": "ai-l10n translate src/locales/en/translation.json --languages fr,de,ja,es,ko --update",
"pretranslate": "npm run translate",
"dev": "vite",
"build": "npm run translate && vite build"
}
}LANGUAGES = fr,de,ja,es,ko,zh-CN
translate:
npx ai-l10n translate src/locales/en/translation.json --languages $(LANGUAGES) --update
dev: translate
npx vite
build: translate
npx vite build有关 CI/CD 集成和自动化的更多详细信息,请参阅我们的 本地化自动化指南
直接在 VS Code 中翻译您的 React i18next JSON 文件。l10n.dev 扩展让您无需离开编辑器即可翻译文件:
现在,您已拥有使用 react-i18next 构建完全本地化 React 应用所需的一切。结合 i18next 成熟的生态系统与 AI 驱动的翻译,快速以任何语言发布您的应用。
react-i18next 为 React 应用提供了完整的、生产级的本地化解决方案。凭借基于 Hooks 的 API、命名空间支持、TypeScript 集成和 SSR 兼容性,它能处理您应用可能有的所有 i18n 需求。
将 react-i18next 与 l10n.dev 的 AI 驱动翻译相结合,消除翻译瓶颈。在几秒钟内翻译您的 JSON 文件,集成到您的 CI/CD 流水线中,并自信地走向全球。
我们的使命是使软件本地化变得快速、实惠且对开发者友好。立即尝试 l10n.dev,看看 AI 如何改变您的 React 本地化工作流。