关于 i18n
i18n 是用于应用国际化开发的参考 Skill,介绍 React 的 i18next 模式和 Next.js 的 next-intl,并提供格式化、翻译文件组织及常见问题建议。
主要功能
- 01React 的 i18next 模式
- 02Next.js 的 next-intl 配置
- 03使用 Intl 格式化日期和数字
- 04ICU 消息格式示例
- 05翻译文件组织方式
适用场景
- 01为 React 界面添加翻译
- 02在 Next.js 应用中配置本地化
- 03检查国际化实现方案
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill i18n安装后在 Claude Code 中输入/i18n确认已加载。
详细介绍
国际化(i18n)
i18next(React — 推荐)
// i18n.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
ns: ['common', 'auth'],
defaultNS: 'common',
interpolation: { escapeValue: false },
});
export default i18n;
// Usage in components
import { useTranslation } from 'react-i18next';
function Welcome() {
const { t } = useTranslation();
return (
<>
<h1>{t('welcome', { name: 'John' })}</h1>
<p>{t('items_count', { count: 5 })}</p>
</>
);
}
翻译文件
// locales/en/common.json
{
"welcome": "Welcome, {{name}}!",
"items_count_one": "{{count}} item",
"items_count_other": "{{count}} items"
}
// locales/it/common.json
{
"welcome": "Benvenuto, {{name}}!",
"items_count_one": "{{count}} elemento",
"items_count_other": "{{count}} elementi"
}
next-intl(Next.js)
// i18n/request.ts
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`../messages/${locale}.json`)).default,
}));
import { useTranslations } from 'next-intl';
function Page() {
const t = useTranslations('HomePage');
return <h1>{t('title')}</h1>;
}
日期和数字格式化
// Use Intl API (built-in, no library needed)
const dateFormatter = new Intl.DateTimeFormat('de-DE', {
year: 'numeric', month: 'long', day: 'numeric',
});
dateFormatter.format(new Date()); // "5. Marz 2026"
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD',
});
currencyFormatter.format(42.5); // "$42.50"
// Relative time
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // "yesterday"
ICU 消息格式
{
"greeting": "{gender, select, male {Mr.} female {Ms.} other {Mx.}} {name}",
"notifications": "{count, plural, =0 {No notifications} one {# notification} other {# notifications}}"
}
翻译文件结构
locales/
├── en/
│ ├── common.json # Shared strings
│ ├── auth.json # Auth-specific
│ └── errors.json # Error messages
├── it/
│ ├── common.json
│ ├── auth.json
│ └── errors.json
反模式
| 反模式 | 修正方法 |
|---|---|
| UI 中的硬编码字符串 | 将所有面向用户的文本提取到翻译文件中 |
| 使用字符串拼接组成句子 | 使用插值({{name}})或 ICU 格式 |
| 手动处理复数逻辑 | 使用内置复数规则(_one、_other) |
| 使用字符串操作格式化日期 | 使用 Intl.DateTimeFormat |
| 没有回退语言 | 始终设置 fallbackLng |
| 巨大的单个翻译文件 | 按命名空间拆分(common、auth、errors) |
生产环境检查清单
- 将所有面向用户的字符串外部化
- 为所有受支持的语言设置复数规则
- 使用
IntlAPI 格式化日期和数字 - 支持 RTL 布局(如适用)
- 检测语言(浏览器语言、用户偏好)
- 建立与译者协作的翻译工作流
- 在 CI 中检测缺失的键
评论
支持 Markdown