i18n
規則
- Next.js App Router:使用
next-intl — useTranslations() 鉤子、NextIntlClientProvider、用於語言偵測的中介軟體
- React SPA:使用
react-i18next — useTranslation() 鉤子、搭配 i18next-http-backend 進行延遲載入的 i18n.init()
- 語言感知路由:
/en/about、/fr/about — 使用中介軟體偵測 Accept-Language 標頭並重新導向
- 翻譯檔案:每個語言每個命名空間一個 JSON 檔案 —
messages/en/common.json、messages/fr/common.json
- 命名空間拆分:每個功能/頁面一個命名空間 —
auth.json、dashboard.json、settings.json — 僅載入頁面所需的內容
- 複數形式:使用 ICU 訊息格式 —
{count, plural, one {# 個項目} other {# 個項目}}
- 插值:
t('greeting', { name }) — 絕對不要拼接已翻譯的文字
- 日期/數字/貨幣:使用
Intl.DateTimeFormat、Intl.NumberFormat — 絕對不要硬編碼格式
- RTL 支援:在
<html> 上使用 dir="rtl",使用 CSS 邏輯屬性(margin-inline-start 而非 margin-left),用阿拉伯語/希伯來語測試
模式
import createMiddleware from "next-intl/middleware";
export default createMiddleware({
locales: ["en", "fr", "de", "ar"],
defaultLocale: "en",
});
import { useTranslations } from "next-intl";
function ProductCard({ price, date }: { price: number; date: Date }) {
const t = useTranslations("products");
const format = useFormatter();
return (
<div>
<h2>{t("title")}</h2>
<p>{format.number(price, { style: "currency", currency: "USD" })}</p>
<p>{format.dateTime(date, { dateStyle: "medium" })}</p>
</div>
);
}
應避免的事項
- 硬編碼使用者面向的字串 — 每個字串都必須透過
t() 處理
- 對翻譯文字進行字串拼接 — 使用插值或 ICU 格式
- 預先載入所有語言 — 按語言和命名空間進行延遲載入
- 使用 CSS 的
left/right 進行版面佈局 — 使用邏輯屬性以確保 RTL 相容性
- 僅將語言儲存在 localStorage — 使用基於 URL 的語言以利 SEO 和共享