ThinkJS 国际化(i18n)实战指南:think-i18n 的翻译、日期与数字本地化方案
ThinkJS 国际化(i18n)实战指南:think-i18n 的翻译、日期与数字本地化方案
think-i18n 是 ThinkJS 3.0 的官方国际化(i18n)扩展方案,它基于 Jed、Moment 与 Numeral 三个成熟库,将「文本翻译、日期时间显示、数字格式」三类本地化需求统一到一份语言包配置中。本文将从安装接入、语言包结构、Controller/View 中的调用方式、完整配置项逐一展开,并结合仓库源码与真实示例(think-demo)剖析其底层实现,帮助你在一套 ThinkJS 应用中轻松实现多语言站点,而无需在代码里到处切换 locale。
核心特性
根据 packages/think-i18n/README.md,think-i18n 的主要能力包括:
- 三位一体的 i18n 方案:同时覆盖翻译(translation)、日期时间(datetime)与数字(number)显示;
- 按语言定制格式:每个 locale 可独立定义日期格式与数字格式;
- 开箱即用:只需在语言包文件中定义期望的格式与翻译,库会自动在对应时刻应用「locale 设置」,省去繁琐的语言切换逻辑;
- 易于调试:通过
debugLocale可直接锁定某个语言环境进行调试; - 语言获取流程可定制:
getLocale支持从请求头、URL 查询参数、Cookie 或自定义函数中获取,完全适配你的业务场景; - Moment 与 Numeral 被隔离:通过
bundledDependencies打包在 think-i18n 内部,你仍然可以在系统其他部分自由使用它们,互不干扰。
安装与接入
在 ThinkJS 3.0 项目中安装:
npm install think-i18n --save
随后在 config/extend.js 中注册扩展:
// thinkjs config/extend.js
const createI18n = require('think-i18n');
const path = require('path');
module.exports = [
createI18n({
i18nFolder: path.resolve(__dirname, '../i18n'),
localesMapping(locales) {return 'en';}
})
];
createI18n(options) 的入口实现位于 packages/think-i18n/index.js,它本质上是 (new I18n()).extend(options) 的语法糖。extend() 在 packages/think-i18n/src/i18n.js 中完成三件事:
- 扫描
i18nFolder目录下所有.js文件并加载为语言包配置(loadLocaleConfigs); - 向返回对象注入
controller.getLocale与controller.getI18n两个方法; - 若传入了
app,则监听viewInit事件,在视图初始化时自动把 i18n 实例注入到__字段。
从源码看,i18nFolder 必须是一个真实存在的目录且其中至少有一个 .js 文件,否则会在 prepareOptions(src/i18n.js#L32-L40)与 getConfigFiles(src/i18n.js#L26-L30)阶段抛出断言错误:
missing locale setting, no .js files are found in <i18nFolder>
Locale 语言包:一个文件搞定一类语言
每个语言环境对应 i18nFolder 下的一个 JavaScript 文件(详见示例 i18n_example/en.js 与 i18n_example/cn.js):
module.exports = {
app: think.app, // 若不传入,则 __ 不会自动 assign 进 think-view 实例
localeId,
translation,
dateFormat, // optional
numeralFormat, // optional
}
各字段含义如下:
- localeId:当前语言环境的唯一名称。注意:locale id 必须是小写。
- dateFormat:会通过
moment.locale(localeId, dateFormat)注册到 Moment;若留空,你会得到一个'en'语言环境的 moment 实例。 - numeralFormat:会通过
numeral.locales[localeId] = numeralFormat注册到 Numeral;若留空,你会得到一个'en'语言环境的 numeral 实例。 - translation:等价于 Jed 的
locale_data结构。如果你使用.po文件,Jed 官方推荐使用 po2json(支持 jed 格式转换)来生成translation。
加载与校验的源码级细节
在 loadLocaleSettings(src/i18n.js#L42-L62)中,加载流程依次执行:
- 读取每个语言包文件中的
localeId、dateFormat、numeralFormat、translation; - 若配置了
dateFormat,调用moment.locale(localeId, dateFormat)注册自定义日期格式; - 若配置了
numeralFormat,先取出其中的formats数组单独保存(用于后续自定义数字格式的映射),再调用numeral.locales[localeId] = numeralFormat注册数字格式; - 断言
translation必须是对象,否则抛出missing translation in locale <localeId>, refer to jed locale_data。
以中文语言包 i18n_example/cn.js 为例,dateFormat 是标准的 Moment 语言包结构(月份、星期、longDateFormat、meridiem、relativeTime 等),numeralFormat 则定义了 delimiters(千位分隔符)、abbreviations(千/百万/十亿/兆的中文缩写)、currency.symbol(¥)以及 formats(自定义格式映射):
module.exports = {
localeId: 'cn',
dateFormat: {
months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LLLL: 'YYYY年MMMD日ddddAh点mm分',
// ...
},
// ...
},
numeralFormat: {
delimiters: { thousands: ',', decimal: '.' },
abbreviations: { thousand: '千', million: '百万', billion: '十亿', trillion: '兆' },
currency: { symbol: '¥' },
formats: [
{name: 'currency', format: '0,0[.]00 $'} // numeral(1000).format('currency') === numeral(1000).format('0,0[.]00 $')
]
},
translation: {
"messages": {
"": { "domain": "messages", "lang": "cn", "plural_forms": "nplurals=1; plural=(n != 1);" },
"some key": ["一些键"]
}
// ...
}
}
注意 translation 中每个 domain 需要包含一个 "" 键,用于声明 domain、lang 与 plural_forms(复数规则),这是 Jed locale_data 的标准格式。
在 Controller 与 View 中使用
Controller
扩展注入后,Controller 实例上可直接访问 this.i18n(/*forceLocale*/) 与 this.getLocale()(类型声明见 packages/think-i18n/index.d.ts)。典型用法:
async indexAction(){
this.assign(this.i18n(/*forceLocale*/));
// ...
}
getI18n(locale) 的核心逻辑在 src/i18n.js#L134-L173:
- 若未传入
locale,则取debugLocale || localesMapping(this.getLocale()); locale必须是字符串,否则抛出controller.getI18n(locale), locale must be string or undefined;- 实例会缓存当前 locale(
curLocale),相同 locale 下重复调用直接返回缓存实例; - 若
localeConfigs中找不到对应语言包,抛出locale config <locale> not found; - 最终构造一个
__函数(内部调用jed.gettext(key)),并挂载__.jed、__.moment、__.numeral三个属性返回。
在 getI18nInstance 中还会根据语言包是否定义了 dateFormat / numeralFormat,决定将 Moment、Numeral 的全局 locale 切换到当前 locale 还是 'en'。对应的测试用例见 test/i18n_extend.js。
View(以 nunjucks 为例)
如果你使用了 think-view,think-i18n 会在视图初始化时自动注入 i18n 实例到 __ 字段,等价于 this.assign('__', this.getI18n())。该行为由 app.on('viewInit', ...) 实现(src/i18n.js#L175-L179),而 viewInit 事件由 think-view/lib/controller.js 在视图实例化时发出。
模板中的典型用法:
{{ __('some key') }} translation
{{ __.jed.dgettext('domain', 'some key') }} translation in specify domain
{{ __.moment().format('llll') }} datetime format
{{ __.numeral(1000).format('currency') }} number format (see numberFormat.formats)
这里 __ 是一个函数对象,因此既可以像普通函数一样被调用(__('some key')),也可以访问其上的 jed、moment、numeral 属性。仓库中的真实示例 think-demo/view/index_index.html 完整展示了这四种用法,并通过 /?locale=en-us、/?locale=zh-cn 链接实现语言切换。
完整配置项(Complete Options)
| 配置项 | 类型 | 说明 |
|---|---|---|
| i18nFolder | string | 存放所有语言包(Locale Settings)文件的目录路径 |
| localesMapping | function(locales) => localeId | 给定一组可能的 locales,返回最终使用的 localeId |
| getLocale | object / function | 当前语言获取策略(见下) |
| debugLocale | localeId 字符串 | 调试时强制使用的语言 |
| jedOptions | object | 传给 Jed 的选项,如 domain、missing_key_callback,详见 Jed 文档 |
i18nFolder
必填项,必须是字符串且指向存在的目录(源码中通过 isString 与 isDirectory 断言校验)。
localesMapping
必填函数,接收 getLocale() 返回的候选 locale 列表,返回一个具体的 localeId。在 demo 中的实现见 think-demo/src/config/extend.js,它通过正则匹配 cn* / en* 前缀并带有默认回退值:
var regCn = /^cn.*$/;
var regEn = /^en.*$/;
const i18n = createI18n({
app: think.app,
i18nFolder: path.resolve(__dirname, './locales'),
getLocale: {by: 'query', name: 'locale'},
localesMapping(locales) {
for(l of locales) {
if(regCn.test(l)) return 'zh-cn';
if(regEn.test(l)) return 'en-us';
}
return 'zh-cn'; // 默认
}
});
(注:demo 配置中还出现 defaultLocale 字段,但从 src/i18n.js#L100 的解构可知,核心实现并不读取该字段,默认语言完全由 localesMapping 的返回值决定。)
getLocale:如何定位当前语言
默认逻辑:读取请求头 accept-language,若设置则按 , 分割返回候选列表,否则返回空数组(src/i18n.js#L103-L111)。对应测试见 test/i18n_extend.js。
也可以按对象或函数形式定制:
- 从 URL 查询参数获取:
{by: 'query', name: 'locale'},即从?locale=xxx中取值。源码通过正则${name}=(<a href="https://link.gitcode.com/i/6b06eed476ca0b6e449ab1a9f8bd0b0b" target="_blank">^&]*)匹配decodeURIComponent(url)得到([src/i18n.js#L112-L119),能正确处理 URL 编码与多参数场景,对应测试见 test/i18n_extend.js。 - 从 Cookie 获取:
{by: 'cookie', name: 'locale'},使用cookie库解析请求头中的 cookie(src/i18n.js#L120-L126),对应测试见 test/i18n_extend.js。 - 自定义函数:
function(ctx) {return locale;},接收 Koa 风格的ctx对象,返回 locale 字符串或数组。注意:当getLocale为对象时,by必须是'cookie'或'query',且必须提供name字段,否则在validateGetLocale(src/i18n.js#L14-L24)中会被断言拦截。
debugLocale
设置为某个 localeId 后,getI18n() 在未传参数时会优先使用该值(src/i18n.js#L135-L137),便于在开发阶段固定语言进行调试。
jedOptions
默认值为 {},最终传给 Jed 的选项为:
Object.assign(jedOptions, {locale_data: <your locale translation>})
即你可以在 jedOptions 中指定 domain、missing_key_callback 等 Jed 支持的能力,locale_data 会自动由当前语言包的 translation 填充(src/i18n.js#L151)。
设计思想:为什么把三个库的 i18n 配置合并在一起?
把 Jed(翻译)、Moment(日期)、Numeral(数字)三者的 i18n 配置统一到一个语言包中的原因,是透明且可组合的灵活性:你可以针对每个 locale 自由组合消息、日期与数字的行为。例如,你的网站在中国运营,需要提供英文翻译,但希望保留人民币符号,就可以在 en.js 语言包中组合「英文翻译 + 中文日期 + 中文货币」:
// locale setting of en.js
module.exports = {
localeId: 'en_ch',
translation: require('../english.po.json'),
dateFormat: require('../moment/en.json'),
numeralFormat: require('../numeral/en.json')
};
作者的另一个建议是始终使用自定义格式,而不要硬编码格式字符串:
- 使用
__.moment().format('llll')而非moment().format('YYYY-MM-dd HH:mm'); - 使用
__.numeral(value).format('customFormat')而非numeral(value).format('00.00$')。
这样格式细节完全由语言包决定,切换语言时展示层代码无需任何改动。
注意事项(Notice)
- locale id 必须是小写,例如
en、cn、zh-cn、en-us。 - 如果你定义了
en语言包,它会覆盖 Numeral 内置的默认enlocale。 - 为了让你在系统其他部分仍能自由使用 Moment 和 Numeral,这两个库通过
package.json中的bundledDependencies隔离在 think-i18n 内部(见 packages/think-i18n/package.json)。 - Numeral 本身不支持按 locale 自定义格式,think-i18n 通过一些小技巧实现了该能力:在
loadLocaleSettings时把每个语言包的numeralFormat.formats提取出来,然后在applyNumeralCustomFormat(src/i18n.js#L64-L87)中注册一个名为think_i18n_numeral_format的自定义格式处理器——其正则/^.+$/匹配任意格式名,并在调用时查表找到对应的真实格式后转调numeral.format。因此你可以放心地在每个语言包的numeralFormat.formats中配置自定义格式,例如 i18n_example/en.js 中的{name: 'currency', format: '$ 0,0[.]00'}。
在仓库中查看更多实例
- 完整语言包示例:packages/think-i18n/i18n_example/en.js、packages/think-i18n/i18n_example/cn.js;
- 核心实现:packages/think-i18n/src/i18n.js;
- 单元测试(覆盖 getLocale 各分支、viewInit 注入、moment/numeral locale 切换等):packages/think-i18n/test/i18n.js、packages/think-i18n/test/i18n_extend.js;
- 真实接入 Demo:ThinkJS 官方示例 think-demo/src/config/extend.js(含
zh-CN.js/en-US.js语言包)与模板 think-demo/view/index_index.html。