国际化 i18n
i18n = "internationalization"(中间 18 字母)。让一个产品能用多种语言、多个地区惯例(日期 / 货币 / 数字格式)。
i18n internationalization 把产品改造成"能国际化"
l10n localization 针对具体地区 / 语言做翻译
g11n globalization 整体规划(技术 + 业务)
按这个顺序:架构(i18n)→ 翻译(l10n)→ 文化适配(g11n)一、不只是翻译
中文 / 英文 → 翻译
日期格式 2024/05/04 vs May 4, 2024 vs 04 May 2024
数字格式 1,000.50 vs 1.000,50 vs 1 000.50
货币格式 ¥100 / $100 / 100 €
单位 公里 vs 英里,摄氏 vs 华氏
时区 同一时间在不同时区显示不同
复数 "1 item" / "2 items"(英语 2 种,俄语 3 种,阿拉伯 6 种)
排序 中文按拼音 / 笔画,德文 ä 排在哪里
方向 LTR(英文)vs RTL(阿拉伯文 / 希伯来文)
颜色 / 图像 中国红色喜庆,西方红色警告
法规 GDPR / CCPA / 隐私 / 服务条款翻译只占 i18n 工作量的 50%。架构早期没考虑这些,后期改起来要命。
二、技术架构(早期就要规划)
1. 文本不能写死
// ❌
<h1>Welcome to my app</h1>
<button>Submit</button>
// ✅
<h1>{t('welcome.title')}</h1>
<button>{t('action.submit')}</button>所有面向用户的字符串走翻译函数。包括:
- 页面文本
- 错误信息
- 表单 placeholder / label
- alt / title / aria-label
- toast / 通知
- 邮件模板
- 后端返回的可见字符串
2. 翻译文件
// locales/en.json
{
"welcome": { "title": "Welcome" },
"action": { "submit": "Submit", "cancel": "Cancel" }
}
// locales/zh.json
{
"welcome": { "title": "欢迎" },
"action": { "submit": "提交", "cancel": "取消" }
}3. 文本不能拼接
// ❌ 英文 "Hello, Alice!"
<p>Hello, {name}!</p>
// ❌ 翻译时被打断,翻译者不知道 "Hello, " 后面跟啥
<p>{t('hello')}, {name}!</p>
// ✅ 占位符
<p>{t('greeting', { name })}</p>// en.json
{ "greeting": "Hello, {{name}}!" }
// zh.json
{ "greeting": "你好,{{name}}!" }
// fr.json
{ "greeting": "Bonjour, {{name}} !" } // 法语 ! 前要空格,中文不要4. 复数
英语:1 item / 2 items(2 种) 俄语:1 элемент / 2 элемента / 5 элементов(3 种) 阿拉伯:6 种
// ❌
<p>{count} item{count > 1 ? 's' : ''}</p>
// ✅ ICU 格式
{t('items', { count })}{
"items": "{count, plural, =0{no items} one{# item} other{# items}}"
}或 i18next 的 _one _other 后缀:
{
"items_one": "{{count}} item",
"items_other": "{{count}} items"
}三、JS 国际化原生 API:Intl
浏览器自带强大的 i18n API,很多场景不需要库:
1. 数字 / 货币 / 单位
new Intl.NumberFormat('en-US').format(1000.5); // "1,000.5"
new Intl.NumberFormat('de-DE').format(1000.5); // "1.000,5"
new Intl.NumberFormat('fr-FR').format(1000.5); // "1 000,5"
new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD'
}).format(99.5); // "$99.50"
new Intl.NumberFormat('zh-CN', {
style: 'currency', currency: 'CNY'
}).format(99.5); // "¥99.50"
new Intl.NumberFormat('en-US', {
style: 'unit', unit: 'kilometer-per-hour'
}).format(60); // "60 km/h"2. 日期 / 时间
const d = new Date('2024-05-04T10:30:00');
new Intl.DateTimeFormat('en-US').format(d); // "5/4/2024"
new Intl.DateTimeFormat('zh-CN').format(d); // "2024/5/4"
new Intl.DateTimeFormat('en-GB').format(d); // "04/05/2024"
new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
hour: 'numeric', minute: 'numeric',
}).format(d);
// "May 4, 2024 at 10:30 AM"3. 相对时间
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // "yesterday"
rtf.format(2, 'hour'); // "in 2 hours"
const rtfZh = new Intl.RelativeTimeFormat('zh-CN');
rtfZh.format(-1, 'day'); // "1天前"4. 复数规则
const pr = new Intl.PluralRules('en-US');
pr.select(1); // "one"
pr.select(2); // "other"
const prAr = new Intl.PluralRules('ar');
prAr.select(0); // "zero"
prAr.select(1); // "one"
prAr.select(2); // "two"
prAr.select(5); // "few"
prAr.select(15); // "many"5. 列表
const lf = new Intl.ListFormat('en-US');
lf.format(['Apple', 'Orange', 'Banana']); // "Apple, Orange, and Banana"
const lfZh = new Intl.ListFormat('zh-CN');
lfZh.format(['苹果', '橘子', '香蕉']); // "苹果、橘子和香蕉"6. 排序(字符串比较)
const arr = ['Äpfel', 'Apfel', 'Zebra'];
arr.sort(); // ❌ 按 unicode 字节
// ['Apfel', 'Zebra', 'Äpfel']
arr.sort(new Intl.Collator('de-DE').compare); // ✅ 德语规则
// ['Apfel', 'Äpfel', 'Zebra']
new Intl.Collator('zh-CN').compare('张', '王'); // 按拼音
new Intl.Collator('zh-CN-u-co-stroke').compare('张', '王'); // 按笔画7. 区段(SegmentLine)
const seg = new Intl.Segmenter('zh-CN', { granularity: 'word' });
[...seg.segment('我爱北京天安门')].map(s => s.segment);
// ['我', '爱', '北京', '天安门']中文分词 / 日文分词都自动!省掉一个分词库。
记住:做 i18n 先看 Intl 能不能搞定,再考虑库。
四、i18n 库选型
React 主流:i18next
pnpm add i18next react-i18next i18next-browser-languagedetectorimport i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import en from './locales/en.json';
import zh from './locales/zh.json';
i18n.use(LanguageDetector).use(initReactI18next).init({
resources: { en: { translation: en }, zh: { translation: zh } },
fallbackLng: 'en',
interpolation: { escapeValue: false },
});import { useTranslation } from 'react-i18next';
function App() {
const { t, i18n } = useTranslation();
return (
<div>
<h1>{t('welcome.title')}</h1>
<p>{t('greeting', { name: 'Alice' })}</p>
<button onClick={() => i18n.changeLanguage('zh')}>中文</button>
<button onClick={() => i18n.changeLanguage('en')}>EN</button>
</div>
);
}Vue:vue-i18n
import { createI18n } from 'vue-i18n';
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: { en, zh },
});
app.use(i18n);<template>
<h1>{{ $t('welcome.title') }}</h1>
<button @click="$i18n.locale = 'zh'">中文</button>
</template>Next.js:next-intl(2025 推荐)
App Router 的官方推荐方案:
pnpm add next-intl// src/i18n.ts
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`./messages/${locale}.json`)).default,
}));import { useTranslations } from 'next-intl';
export default function Home() {
const t = useTranslations('Home');
return <h1>{t('title')}</h1>;
}URL 自动 /en/... /zh/...,SSR 完美。
框架无关:FormatJS / @formatjs/intl
ICU 标准实现,最严格(Airbnb / Yahoo 用):
import { createIntl } from '@formatjs/intl';
const intl = createIntl({ locale: 'en-US', messages });
intl.formatMessage({ id: 'greeting' }, { name: 'Alice' });适合严格 ICU 格式项目。
轻量:lingui / next-intl
类型安全 + 编译时优化,体积更小。
五、ICU MessageFormat
ICU 是 i18n 工业标准,处理复数 / 性别 / 选择:
Plural:
{count, plural, =0{No items} one{# item} other{# items}}
Selector(枚举):
{gender, select, male{He} female{She} other{They}} likes this
Number:
{amount, number, currency}
Date:
{date, date, medium}
复合:
{count, plural,
=0 {You have no messages}
one {You have 1 message from {sender}}
other {You have # messages from {sender}}}i18next / FormatJS / next-intl 都支持 ICU。记住占位符语法,翻译者用。
六、翻译工作流
1. 翻译来源
小项目 : 自己翻 / 找 ChatGPT 翻
中型 : 找翻译公司或自由翻译
大型 : 用翻译管理平台(TMS)2. TMS 平台
Crowdin 最流行,GitHub 集成好
Lokalise 企业级
Phrase 老牌
Tolgee 开源,可自托管
Transifex 社区翻译工作流:
- 代码里
t('xxx')→ 提取脚本扫描,找出新 key - 推送 key 到 TMS → 翻译者翻译
- 拉回翻译 → 部署
3. 命名规范
按页面 / 模块组织:
home.title
home.cta
user.profile.name
errors.network
forms.email.required
forms.email.invalid
而不是:
greeting1, greeting2 ← 看不出语境,翻译者迷茫4. 给翻译者上下文
// ❌ 翻译者不知道 "save" 是按钮还是名词
{ "save": "Save" }
// ✅ 加 context
{ "saveButton": "Save" }
{ "savedItems": "Saved" }或用 i18next 的 context:
{ "save": "Save", "save_male": "He saved", "save_female": "She saved" }t('save', { context: gender });5. 截屏 / 标注
工业级 i18n 实践:给每个 key 截屏让翻译者看到上下文。Crowdin / Lokalise 都支持。
七、RTL 支持(阿拉伯文 / 希伯来文)
英文 / 中文 / 日文:LTR(从左到右)
阿拉伯 / 希伯来 / 波斯:RTL(从右到左)
不只是文字反方向,整个布局都要镜像:
导航 logo 在右,菜单在左
侧栏在右
按钮顺序反
滑块从右到左
...实现
<html lang="ar" dir="rtl">CSS 用逻辑属性(2024+ 主流):
/* ❌ 只对 LTR 友好 */
.box {
margin-left: 16px;
padding-right: 8px;
text-align: left;
border-left: 1px solid;
}
/* ✅ 逻辑属性,自动适配方向 */
.box {
margin-inline-start: 16px; LTR 左,RTL 右
padding-inline-end: 8px;
text-align: start; LTR 左,RTL 右
border-inline-start: 1px solid;
}/* 物理属性 逻辑属性 */
margin-left → margin-inline-start
margin-right → margin-inline-end
padding-top → padding-block-start
left: 0 → inset-inline-start: 0
text-align: left → text-align: start
border-radius → border-start-start-radiusTailwind 4 内置 logical 类:ms-4(margin-start)、me-4(margin-end)、ps-4、pe-4、text-start。
问题点
- 数字仍是 LTR(
123不会变321) - ARIA + 表单提示也要翻译
- 图标方向要翻转(返回箭头 ← 变 →)
[dir="rtl"] .arrow-back {
transform: scaleX(-1);
}测试:浏览器开发工具能切换 dir,或用 Chrome 扩展模拟。
八、URL 与路由策略
方案 URL SEO 分享
1. 子路径(推荐) /en/about /zh/about ✅ ✅
2. 子域 en.app.com / zh.app.com ✅ ⚠️
3. 顶级域 app.com / app.cn ✅✅ ⚠️
4. 查询参数 /about?lang=zh ❌ ✅
5. cookie / header 不带 URL ❌ ❌默认推荐子路径:Next.js / Nuxt / Astro 都内置支持。
自动检测
// 优先级
1. URL 里指定的 → /zh/...
2. cookie / localStorage 上次选择
3. Accept-Language 头
4. 默认语言(en)// 简单实现
function detectLocale(req) {
const cookie = req.cookies.lang;
if (cookie) return cookie;
const accepted = req.headers['accept-language'];
// 解析 'zh-CN,zh;q=0.9,en;q=0.8'
// ...
return matchLocale(accepted);
}hreflang(SEO)
<link rel="alternate" hreflang="en" href="https://app.com/en/page">
<link rel="alternate" hreflang="zh-CN" href="https://app.com/zh/page">
<link rel="alternate" hreflang="x-default" href="https://app.com/page">告诉 Google "这页有这些语言版本",不会被当成重复内容。
九、时区
const d = new Date('2024-05-04T10:00:00Z'); // UTC
// 转用户时区显示
new Intl.DateTimeFormat('en-US', {
dateStyle: 'medium', timeStyle: 'short',
timeZone: 'America/New_York', // 或 'auto' 用浏览器时区
}).format(d);
// "May 4, 2024, 6:00 AM"原则
存储:永远 UTC(数据库 TIMESTAMPTZ,API 返 ISO)
传输:UTC ISO 字符串("2024-05-04T10:00:00Z")
显示:转用户时区 + 用户语言库
原生 Intl + Date 简单场景够
date-fns 函数式 + 轻
date-fns-tz + 时区
Day.js moment.js 的现代替代,小
Luxon 时区强,API 现代
Temporal API(2024+ 提案) 标准化新 Date(还在打磨)// date-fns-tz
import { format, toZonedTime } from 'date-fns-tz';
const userTz = Intl.DateTimeFormat().resolvedOptions().timeZone; // 'Asia/Shanghai'
const local = toZonedTime(utc, userTz);
format(local, 'yyyy-MM-dd HH:mm', { timeZone: userTz });十、SSR 与 i18n
1. 服务端要知道 locale
// 中间件
export function middleware(req) {
const locale = detectLocale(req);
const url = new URL(req.url);
if (!url.pathname.startsWith(`/${locale}`)) {
return NextResponse.redirect(`/${locale}${url.pathname}`);
}
}2. 服务端渲染时翻译
next-intl / next-i18next 都内置:SSR 时用对应语言渲染 HTML,首屏不闪烁。
3. 静态生成多语言
build 时生成:
/en/about/index.html
/zh/about/index.html
/fr/about/index.html// Next.js
export async function generateStaticParams() {
return ['en', 'zh', 'fr'].map(locale => ({ locale }));
}十一、常见 Trap
Trap 1:复数处理偷懒
// ❌
`${count} item${count > 1 ? 's' : ''}`
// ❌ 0 也是 "0 items" 没问题,但俄文 / 阿拉伯 / 中文不一样中文没"复数变化",但很多语言有。用 ICU plural。
Trap 2:翻译里夹 HTML
{ "agree": "I agree to the <a href='/terms'>Terms</a>" }容易出错,翻译者改坏 HTML。i18n 库提供"组件插槽":
// react-i18next Trans 组件
<Trans i18nKey="agree">
I agree to the <a href="/terms">Terms</a>
</Trans>{ "agree": "I agree to the <0>Terms</0>" }翻译者只动文字,不碰 tag。
Trap 3:文字长度变化
英文 "Save"(4 字符)→ 德文 "Speichern"(9 字符)→ 按钮溢出
英文 "Welcome"(7)→ 中文 "欢迎"(2)→ 留白难看设计要预留空间(40% 增长),按钮 / 输入框宽度自适应,不要固定宽。
Trap 4:日期 / 数字直接拼
`Today is ${date.toString()}` // 浏览器默认格式,不是 i18n总是用 Intl 或库。
Trap 5:文本里有性别
英文 He / She / They → 翻译需要知道性别
中文 他 / 她 / 它 → 同问题要么用 ICU select,要么避免性别(用 "the user" / "this person")。
Trap 6:图片里有文字
banner.png 里画了 "Save 50%" → 翻译时整个图重做文字应该是 HTML 文字叠图上,不要嵌入图片。
Trap 7:culturally insensitive
红色:中国喜庆,西方警告
拇指 👍:多数文化 OK,中东侮辱
4 / 13:不同文化忌讳
菜单图标 🍴(刀叉)在素食 / 印度宗教用户那不舒服视觉设计要做文化审核。
十二、i18n checklist
架构
- [ ] 所有文本走翻译函数
- [ ] 翻译文件按模块组织
- [ ] 占位符 + ICU 复数
- [ ] 日期 / 数字 / 货币用 Intl
- [ ] 时间存 UTC,显示转用户时区
URL / SEO
- [ ] 子路径
/zh/* - [ ] 自动检测 + 用户可切换
- [ ] hreflang 标签
- [ ] 翻译过的 sitemap
UI / UX
- [ ] 留白预留 40%(德文 / 法文长)
- [ ] 切语言不刷新页面 / SSR 不闪
- [ ] RTL 支持(用逻辑属性)
- [ ] 截屏给翻译者看上下文
工程
- [ ] CI 跑提取脚本,新 key 自动同步 TMS
- [ ] 缺翻译 fallback 到默认语言
- [ ] 翻译懒加载(只加载当前语言)
- [ ] 类型安全(
t('xxx')不存在的 key 编译报错)
文化
- [ ] 颜色 / 图标过文化审核
- [ ] 法规(GDPR / 隐私政策)各地区独立
- [ ] 客服时区 / 联系方式
- [ ] 货币 / 支付方式 / 税
十三、心智模型
i18n 三层:
1. 文本翻译 90% 工程师只做这层
2. 区域格式 数字 / 日期 / 货币 / 时区(用 Intl)
3. 文化适配 RTL / 颜色 / 法规 / 设计
技术栈推荐(2025):
React: react-i18next 或 next-intl(Next.js)
Vue: vue-i18n
通用: Intl(原生)+ FormatJS / lingui
工作流:
代码 t('key') → 提取 → TMS 翻译 → 拉回 → 部署
关键原则:
- 文本不能拼接,用占位符
- 复数用 ICU,不要 if-else
- 时间存 UTC,显示转用户时区
- URL 用 /lang/ 前缀
- CSS 用 logical properties(支持 RTL)十四、推荐学习路径
- 这一篇 + Intl API 文档(MDN,1 小时)
- 给现有项目加 react-i18next(几小时)
- 研究 next-intl(如果 Next 项目)
- 做一个简单 RTL demo
- 看 W3C i18n 工作组博客 对文化坑更敏感
十五、参考资源
- MDN Intl:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
- i18next:https://www.i18next.com
- react-i18next:https://react.i18next.com
- next-intl:https://next-intl-docs.vercel.app
- vue-i18n:https://vue-i18n.intlify.dev
- FormatJS:https://formatjs.io
- ICU MessageFormat:https://unicode-org.github.io/icu/userguide/format_parse/messages/
- Crowdin / Lokalise / Tolgee 平台
下一篇 42 讲桌面端:Electron 与 Tauri。