name: internationalization-helper description: 提取硬编码字符串用于国际化,管理翻译文件,并确保区域覆盖。适用于多语言应用、翻译或用户提及i18n、本地化或语言时使用。 allowed-tools: Read, Grep, Glob, Write, Edit
国际化助手
帮助管理多语言应用程序中的国际化(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 (内置)
查找导入、配置文件或翻译目录。
2. 查找硬编码字符串
搜索未翻译的文本:
// 错误:硬编码
<button>提交</button>
<p>欢迎,{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": "提交",
"cancel": "取消"
},
"welcome": {
"message": "欢迎,{{name}}!"
}
}
Gettext格式(.po):
msgid "submit_button"
msgstr "提交"
msgid "welcome_message"
msgstr "欢迎,%(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 个项目"
t('items', { count: 1 }) // "1 个项目"
t('items', { count: 5 }) // "5 个项目"
// 翻译文件
{
"items_zero": "{{count}} 个项目",
"items_one": "{{count}} 个项目",
"items_other": "{{count}} 个项目"
}
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:翻译文件模板