i18n 與本地化
國際化(i18n)與本地化(L10n)的最佳實務。
1. 核心概念
| 術語 | 意義 |
|---|
| i18n | 國際化 – 讓應用程式具備翻譯能力 |
| L10n | 本地化 – 實際的翻譯內容 |
| Locale | 語言 + 區域(例如 en-US、tr-TR) |
| RTL | 從右到左的語言(阿拉伯文、希伯來文) |
2. 何時使用 i18n
| 專案類型 | 需要 i18n? |
|---|
| 公開網站 | ✅ 是 |
| SaaS 產品 | ✅ 是 |
| 內部工具 | ⚠️ 視情況 |
| 單一區域應用程式 | ⚠️ 考慮未來需求 |
| 個人專案 | ❌ 可選擇 |
3. 實作模式
React(react-i18next)
import { useTranslation } from 'react-i18next';
function Welcome() {
const { t } = useTranslation();
return <h1>{t('welcome.title')}</h1>;
}
Next.js(next-intl)
import { useTranslations } from 'next-intl';
export default function Page() {
const t = useTranslations('Home');
return <h1>{t('title')}</h1>;
}
Python(gettext)
from gettext import gettext as _
print(_("歡迎使用我們的應用程式"))
4. 檔案結構
locales/
├── en/
│ ├── common.json
│ ├── auth.json
│ └── errors.json
├── tr/
│ ├── common.json
│ ├── auth.json
│ └── errors.json
└── ar/ # RTL
└── ...
5. 最佳實務
應該 ✅
- 使用翻譯鍵(translation keys),而非原始文字
- 按功能模組劃分翻譯命名空間
- 支援複數形式
- 針對每個語言環境處理日期/數字格式
- 從一開始就規劃 RTL
- 對複雜字串使用 ICU 訊息格式
不應該 ❌
- 在元件中硬編碼字串
- 連接翻譯後的字串
- 假設文字長度(德文會長 30%)
- 忘記 RTL 版面配置
- 在同一個檔案中混合多種語言
6. 常見問題
| 問題 | 解決方案 |
|---|
| 缺少翻譯 | 回退到預設語言 |
| 硬編碼字串 | 使用 linter/檢查指令碼 |
| 日期格式 | 使用 Intl.DateTimeFormat |
| 數字格式 | 使用 Intl.NumberFormat |
| 複數形式 | 使用 ICU 訊息格式 |
7. RTL 支援
.container {
margin-inline-start: 1rem;
padding-inline-end: 1rem;
}
[dir="rtl"] .icon {
transform: scaleX(-1);
}
8. 檢查清單
出貨前:
指令碼
| 指令碼 | 用途 | 命令 |
|---|
scripts/i18n_checker.py | 偵測硬編碼字串與缺少的翻譯 | python scripts/i18n_checker.py <專案路徑> |
使用時機
此技能適用於執行概述中所描述的工作流程或動作。
連結
- 領域: [[Software Entwicklung]]
- 類別: [[Software Architektur]]
- 檔案:
- 導航: [[Skills Uebersicht]]、[[Home]]