幫助中心

使用 i18next 進行 React 本地化

為全球受眾構建 React 應用程式需要強大的國際化 (i18n) 策略。react-i18next 是最受歡迎的 React 本地化函式庫,建立在經過實戰檢驗的 i18next 框架之上。本指南將引導您完成本地化 React 應用程式所需的一切——從初始設定到利用 AI 驅動翻譯實現生產級自動化。

為什麼選擇 react-i18next 進行 React 本地化?

react-i18next 是 React 國際化的事實標準,受到全球數千個生產環境應用程式的信賴。以下是開發人員選擇它的原因:

  • 以 Hooks 為優先的 API - useTranslation() Hook 提供了簡潔、符合 React 風格的整合,並在語言變更時自動重新渲染。
  • 豐富的生態系統 - 提供語言偵測、HTTP 後端、快取等外掛程式。無需重新發明輪子即可擴充功能。
  • JSON 翻譯格式 - 使用標準 JSON 檔案,易於編輯、版本控制,並能與翻譯工具和 AI 服務整合。
  • 命名空間支援 - 將翻譯組織成邏輯群組(如 auth、dashboard、errors),以提高可維護性並支援延遲載入。
  • 支援 SSR 與 Next.js - 與伺服器端渲染、React Server Components 和 Next.js App Router 無縫協作。
  • TypeScript 支援 - 為翻譯鍵提供完整的型別安全與自動完成功能,在編譯時即可捕捉缺失的鍵。

安裝

安裝 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.tsx

翻譯 JSON 檔案格式

react-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"
  }
}
  • 巢狀鍵 - 以層次結構組織翻譯(例如 welcome.title, nav.home),以保持結構清晰。
  • 插值 - 使用 {{variableName}} 語法來處理執行時插入的動態值。
  • 複數形式 - 新增 _one 和 _other 後綴(或針對複雜語言使用 _zero, _two, _few, _many)以進行自動複數處理。
  • 上下文 - 在需要時使用 _male, _female 後綴進行性別特定的翻譯。

設定 i18next

i18next 支援兩種主要的翻譯載入方式:HTTP 後端(延遲載入)和捆綁資源。請根據您的應用需求進行選擇。

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 元件

react-i18next 提供了兩種主要的 API 來翻譯元件:用於程式化存取的 useTranslation Hook,以及用於處理包含 JSX 的富文本的 Trans 元件。

useTranslation Hook

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>
  );
}

用於富文本的 Trans 元件

當翻譯包含 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"
  • 對於英語,請在翻譯鍵中新增 _one 和 _other 後綴
  • 對於具有複雜複數規則的語言(如阿拉伯語、波蘭語、俄語),請根據需要新增 _zero, _two, _few, _many 後綴
  • i18next 會根據目標語言的 CLDR 複數規則自動選擇正確的形式

使用命名空間進行組織

命名空間讓您可以按功能或領域將翻譯拆分為不同的檔案。這能提高可維護性並實現翻譯捆綁包的延遲載入:

// 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 Suspense 與延遲載入

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>;
}

TypeScript 型別安全翻譯鍵

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
型別安全鍵適用於 useTranslation、Trans 元件以及所有 i18next API。缺失或拼錯的鍵會在您的 IDE 中被標記為 TypeScript 錯誤。

使用 Next.js 進行伺服器端渲染

對於使用 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>;
}
  • 在伺服器上為每個請求建立新的 i18next 實例,以防止使用者之間的狀態洩漏
  • 在伺服器端和客戶端渲染中使用相同的翻譯 JSON 檔案
  • 對於複雜的 Next.js 設定,請考慮使用 i18next-resources-to-backend 或 next-intl 作為替代方案

利用 AI 加速翻譯

設定 react-i18next 只是成功了一半,您仍然需要為每個目標語言提供高品質的翻譯。手動翻譯數十個 JSON 檔案既緩慢、昂貴又容易出錯。AI 驅動的翻譯改變了遊戲規則。

為什麼選擇 l10n.dev 進行 React i18next 翻譯?

l10n.dev 是專為開發人員本地化工作流程而設計的。它能原生理解您的 JSON 翻譯檔案,並產生感覺自然而非機器生成的翻譯:

  • 原生 JSON 支援 — 上傳您的 translation.json,即可取回格式完美、可直接使用的 JSON 檔案
  • 具備上下文意識的 AI — 理解您的應用領域,在不同語言間保留技術術語和品牌語氣
  • 插值安全 — 保留 {{variables}}、複數後綴(_one, _other)和巢狀鍵結構
  • 批次翻譯 — 在幾秒鐘內同時翻譯成 10 種以上語言,而非幾天
  • CI/CD 整合 — 使用 ai-l10n npm 套件將翻譯自動化納入您的建置管線

AI 翻譯工作流程

  1. 以英文(或您的基礎語言)編寫原始 translation.json
  2. 上傳至 l10n.dev 或執行 ai-l10n CLI 進行翻譯
  3. AI 為所有目標語言產生上下文準確的翻譯
  4. 將翻譯後的 JSON 檔案放入您的 locales/ 目錄並部署

使用 ai-l10n CLI 自動化翻譯

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

建置整合

將翻譯自動化新增至您的建置管線,以確保翻譯始終保持最新:

package.json 指令碼

{
  "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"
  }
}

Makefile

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 整合與自動化的更多詳細資訊,請參閱我們的 本地化自動化指南

用於 JSON 翻譯的 VS Code 擴充功能

直接從 VS Code 翻譯您的 React i18next JSON 檔案。l10n.dev 擴充功能讓您無需離開編輯器即可翻譯檔案:

運作方式

  1. 從 VS Code Marketplace 安裝 l10n.dev 擴充功能
  2. 開啟您的原始 translation.json 檔案
  3. 右鍵點擊並選擇 'Translate with l10n.dev'
  4. 選擇您的目標語言並立即取得翻譯後的檔案

立即開始本地化您的 React 應用程式

您現在已具備使用 react-i18next 建構完全本地化 React 應用程式所需的一切。結合 i18next 成熟生態系統的強大功能與 AI 驅動的翻譯,快速以任何語言發佈您的應用程式。