為全球受眾構建 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 檔案進行翻譯。鍵支援點標記法、{{variables}} 插值以及內建的複數處理:
// 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 本地化工作流程。