國際化輔助工具
協助管理多語言應用程式中的國際化 (i18n) 與本地化 (l10n)。
使用時機
- 使用者要求 i18n 支援
- 新增語言
- 尋找未翻譯的字串
- 管理翻譯檔案
- 使用者提及「翻譯」、「i18n」、「l10n」、「語言環境」
指示
1. 偵測 i18n 框架
JavaScript/React:
- react-i18next
- react-intl (FormatJS)
- i18next
- LinguiJS
Vue:
- vue-i18n
Python:
- gettext
- Django i18n
- Flask-Babel
Ruby/Rails:
- I18n gem(內建)
尋找 imports、設定檔或翻譯目錄。
2. 尋找硬編碼字串
搜尋未翻譯的文字:
// 錯誤:硬編碼
<button>Submit</button>
<p>Welcome, {user.name}!</p>
// 正確:已翻譯
<button>{t('common.submit')}</button>
<p>{t('welcome.message', { name: user.name })}</p>
搜尋模式:
- JSX/模板標籤中的字串
- 提示/錯誤訊息
- 表單標籤與佔位符
- 按鈕文字
- 驗證訊息
排除:程式碼註解、console.log、測試字串
3. 萃取至翻譯檔案
React-i18next 格式 (JSON):
{
"common": {
"submit": "Submit",
"cancel": "Cancel"
},
"welcome": {
"message": "Welcome, {{name}}!"
}
}
Gettext 格式 (.po):
msgid "submit_button"
msgstr "Submit"
msgid "welcome_message"
msgstr "Welcome, %(name)s!"
4. 組織翻譯金鑰
最佳實踐:
- 按功能命名空間:
users.profile.title - 分組通用字串:
common.buttons.save - 描述上下文而非內容:
errors.login.invalid而非errors.wrong_password - 一致的命名慣例
5. 檢查翻譯覆蓋率
比較語言環境檔案以找出遺漏的翻譯:
en.json: 150 個金鑰
es.json: 142 個金鑰(缺少 8 個)
fr.json: 150 個金鑰 ✓
es.json 缺少:
- users.profile.bio
- settings.privacy.title
[...]
6. 處理複數化
不同語言有不同複數規則:
// react-i18next
t('items', { count: 0 }) // "0 items"
t('items', { count: 1 }) // "1 item"
t('items', { count: 5 }) // "5 items"
// 翻譯檔案
{
"items_zero": "{{count}} items",
"items_one": "{{count}} item",
"items_other": "{{count}} items"
}
7. 日期、時間、數字格式化
使用語言環境感知的格式化:
// 數字
const price = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(29.99);
// 日期
const date = new Intl.DateTimeFormat('fr-FR').format(new Date());
8. RTL(從右到左)支援
針對阿拉伯語、希伯來語:
- CSS:
direction: rtl; - HTML:
<html dir="rtl"> - 邏輯屬性:使用
margin-inline-start取代margin-left
9. 產生翻譯模板
為新語言環境建立模板:
# 從基礎語言複製金鑰,清空值
cp locales/en.json locales/de.json
# 標記為待翻譯
10. 最佳實踐
- 將翻譯放在獨立檔案中
- 使用金鑰,而非原始文字作為金鑰
- 為翻譯人員提供上下文
- 測試長字串(德語通常較長)
- 對於複雜字串使用 ICU MessageFormat
- 避免串接已翻譯的字串
- 萃取所有面向使用者的文字
支援檔案
templates/i18n-config.js:設定範例templates/locale-file.json:翻譯檔案模板