Lingui @lingui/core 运行时深入解析:i18n 实例、宏编译入口与 ICU 消息格式化实现
Lingui @lingui/core 运行时深入解析:i18n 实例、宏编译入口与 ICU 消息格式化实现
@lingui/core 是 Lingui 国际化库的框架无关运行时:它加载编译后的消息目录(catalog)、跟踪当前激活的语言环境(locale),并把 ICU MessageFormat 消息格式化为最终字符串。本文以 packages/core/README.md 为骨架,结合 核心源码、测试用例 与 官方 API 参考文档,完整讲解 i18n 实例的全部 API、@lingui/core/macro 宏入口的工作机制,以及底层 ICU 格式化管线,帮助你既能正确初始化 Lingui,也能理解“编译期目录 + 轻量运行时”这一设计如何在源码层面落地。
包定位:框架无关的 i18n 运行时
Lingui 是一个面向 JavaScript/TypeScript 的轻量国际化库,把编译期宏与 CLI 提取能力带到 React、React Native、Vue、SolidJS、Astro、Svelte 和 Node.js 环境。其中 @lingui/core 承担运行时角色,README 对其定位是:
The Lingui i18n runtime: loads compiled message catalogs, tracks the active locale and formats ICU MessageFormat messages
它有两个关键导出面:
- 默认入口导出
i18n实例,负责加载目录、激活语言、翻译消息; @lingui/core/macro入口导出t、plural、select等宏,它们在构建时被编译为 ICU 消息,依赖 Babel 插件 或 SWC 插件 完成转译。
从 package.json 可以看到几个与运行时设计直接相关的事实:
{
"name": "@lingui/core",
"version": "6.9.0",
"sideEffects": false,
"type": "module",
"exports": {
".": "./dist/index.mjs",
"./macro": {
"browser": "./macro/browser.mjs",
"types": "./macro/index.d.mts",
"default": "./macro/index.mjs"
},
"./package.json": "./package.json"
},
"dependencies": {
"@lingui/babel-plugin-lingui-macro": "workspace:*",
"@lingui/message-utils": "workspace:*"
},
"peerDependencies": {
"babel-plugin-macros": "2 || 3"
},
"peerDependenciesMeta": {
"babel-plugin-macros": { "optional": true }
}
}
可以从中读出三点:
sideEffects: false让打包工具可以安全地做 tree-shaking,这正是 Lingui “2 kb 级运行时”主张的打包基础;./macro的browser条件导出指向一份专门的浏览器 shim(后文详述),说明宏入口在浏览器 bundle 里被专门处理;@lingui/message-utils提供compileMessage,即运行时“按需编译未编译消息”所用的编译器,只在开发环境默认注入。
快速上手:load、activate 与模板字面量宏
README 给出的最小可运行示例如下(完整上下文参见 JavaScript 教程):
import { i18n } from "@lingui/core"
import { t } from "@lingui/core/macro"
import { messages } from "./locales/cs/messages"
i18n.load("cs", messages)
i18n.activate("cs")
function greeting(name) {
return t`Hello ${name}`
}
greeting("Fred") // "Ahoj Fred"
这段代码涉及 Lingui 工作流的两个阶段:
- 构建期:
messages模块由lingui extract与lingui compile命令生成(来自@lingui/cli)。t宏在转译阶段被替换为一个携带消息 ID 与默认消息的描述符,目录则被预编译为可直接执行的 token 数组。README 特别强调:“目录是提前编译好的,因此运行时不携带 MessageFormat 解析器”——这是@lingui/core体积小的核心原因。 - 运行期:
i18n.load("cs", messages)注册目录,i18n.activate("cs")激活语言,之后所有t调用都按捷克语目录查表并格式化。
React 项目通常在此之上再包一层 @lingui/react(I18nProvider、useLingui、Trans 组件),但其底层查表与格式化逻辑仍然全部落在本文讲解的 @lingui/core 中。
全局 i18n 实例与 setupI18n:两种初始化方式
@lingui/core 的默认入口在 src/index.ts 中非常直白:
export { setupI18n, I18n } from "./i18n"
// ...类型导出
// Default i18n object
import { setupI18n } from "./i18n"
export const i18n = setupI18n()
import * as formats from "./formats"
export { formats }
也就是说,导入 i18n 得到的是一个模块级单例,其本质是 setupI18n() 的返回值。setupI18n 定义在 i18n.ts,接受一个可选的 I18nProps 参数:
export type I18nProps = {
locale?: Locale // 初始激活的 locale
locales?: Locales // 备选 locale 列表(用于数字/日期格式化)
messages?: AllMessages // 初始目录
missing?: MissingHandler // 缺失翻译的兜底(字符串或函数)
}
I18n 构造函数(i18n.ts#L109-L121)按顺序处理这三个选项:messages 会走 load,locale/locales 会走 activate(未给 locale 时默认取 "en",见 formats.ts#L7 的 defaultLocale)。还有一个隐藏行为值得注意:
if (process.env.NODE_ENV !== "production") {
this.setMessagesCompiler(compileMessage)
}
即开发环境下自动注册消息编译器,允许你直接用未编译的原始目录调试;生产环境默认不带编译器以保持体积。
官方参考文档给出的典型用法是动态按需加载目录:
import { i18n } from "@lingui/core";
async function activate(locale: string) {
const { messages } = await import(`${locale}/messages.js`);
i18n.loadAndActivate({ locale, messages });
}
activate("cs");
const translation = i18n.t("Hello World");
如果你不使用全局实例而通过 setupI18n() 自建实例(例如多实例场景),需要同时在 Lingui 配置中设置 runtimeConfigModule 指向该模块,以保证宏编译产物引用到同一个 i18n 对象——这一约定在 核心 API 参考 中有专门说明。
目录加载:load、loadAndActivate 与合并语义
I18n 提供三种写入目录的方式,源码都在 i18n.ts:
1. i18n.load(locale, messages) —— 加载单一语言的目录:
i18n.load("en", { Hello: "Hello", "Good bye": "Good bye" })
2. i18n.load(allMessages) —— 一次性加载多语言:
i18n.load({
en: messagesEn,
cs: messagesCs,
})
// 等价于分别调用 i18n.load("en", messagesEn) 与 i18n.load("cs", messagesCs)
重载分发逻辑在 i18n.ts#L169-L185:第一个参数是字符串则走单语言分支,否则按 Object.entries 逐语言加载。两种形式最终都会触发 change 事件。
3. i18n.loadAndActivate({ locale, locales, messages }) —— 加载并立即激活:
i18n.loadAndActivate({ locale: "cs", messages })
对应实现(i18n.ts#L190-L197)是直接覆盖该 locale 的目录(this._messages[this._locale] = messages),而不是合并;locales 是可选的备选 locale 列表(BCP-47 语言标签),专门用于数字与日期格式化——同一国家可能存在多套数字/日期格式时,格式化会按该列表的优先级依次尝试。
合并行为与原型污染防护
load 的私有实现 _load(i18n.ts#L153-L167)有两个细节:
private _load(locale: Locale, messages: Messages) {
// Own-property check so a "__proto__" locale key can't resolve to
// Object.prototype and get merged into (prototype pollution).
const maybeMessages = Object.prototype.hasOwnProperty.call(
this._messages, locale,
) ? this._messages[locale] : undefined
if (!maybeMessages) {
this._messages[locale] = messages
} else {
Object.assign(maybeMessages, messages) // 已加载则合并
}
}
- 合并语义:若该 locale 已有目录,新消息通过
Object.assign并入而非整体替换。i18n.test.ts 中的用例验证了这一点:先load("en", {Hello})再load("en", {World}),结果两个消息都在。 - 安全细节:查找时显式使用
hasOwnProperty,杜绝__proto__这类 key 解析到Object.prototype后被污染合并。测试文件里有专门的一组prototype pollution用例(locale 键为__proto__、消息键为__proto__等)确保该防护生效。
消息与类型的约定
参考文档定义了目录的类型结构:
// 多语言目录映射
type AllMessages = { [locale: string]: Messages }
// 单个语言目录:消息 ID → 翻译(未编译为字符串,编译后为 token 数组)
type Messages = { [messageId: string]: string | Function }
注意:不要手写目录。真实项目中的 messages 模块由 lingui compile 产出(或通过 Vite Plugin、Webpack Loader、Metro Transformer 等构建工具链注入),手写的字符串目录在生产环境无法使用 ICU 特性(详见后文“未编译消息”一节)。
激活语言:activate 与状态读取
i18n.activate(locale<a href="https://link.gitcode.com/i/a11d4fe04c8fa2ec5342405581fd5804" target="_blank">, locales]) 的实现([i18n.ts#L199-L209):
activate(locale: Locale, locales?: Locales) {
if (process.env.NODE_ENV !== "production") {
if (!this._messages[locale]) {
console.warn(`Messages for locale "${locale}" not loaded.`)
}
}
this._locale = locale
this._locales = locales
this.emit("change")
}
行为要点:
- 开发环境下,如果激活一个尚未
load过的 locale,控制台会给出警告(生产环境跳过该检查); - 调用
activate后,i18n.t立即按新 locale 查表,同时广播change事件——这是@lingui/react等上层包实现“语言切换后重渲染”的底层钩子。
实例上还有三个只读属性(i18n.ts#L123-L133):
| 属性 | 含义 |
|---|---|
i18n.locale |
当前激活的 locale(初始为 "") |
i18n.locales |
备选 locale 列表(可能为 undefined) |
i18n.messages |
当前 locale 的目录,未加载时返回 {} |
翻译与格式化:t / _ 的完整解析
i18n._(...) 是规范化的翻译方法,i18n.t 是它的别名(i18n.ts#L292:t: I18n["_"] = this._.bind(this))。它支持两种签名:
// 签名 1:ID + 变量 + 选项
i18n.t(messageId, values?, options?)
// 签名 2:消息描述符
i18n.t(messageDescriptor)
签名 1 的实际用法(摘自 核心 API 参考):
// 简单消息
i18n.t("Hello");
// 带变量
i18n.t("My name is {name}", { name: "Tom" });
// 自定义 messageId + 默认消息(适合 ID 非自然语言的场景,如 msg.id)
i18n.t("msg.id", { name: "Tom" }, { message: "My name is {name}" });
const date = new Date("2014-12-06");
const time = new Date("2014-12-06T17:40:00Z");
// 短日期 / 短时间
i18n.t("It starts on {someDate, date, short}", { someDate: date });
i18n.t("It starts on {someTime, time, short}", { someTime: time });
// 自定义格式名
i18n.t("It starts on {someDate, date, myStyle}", { someDate: date },
{ formats: { myStyle: { day: "numeric" } } });
签名 2 的 messageDescriptor 是一个对象,适合“消息在别处声明、稍后使用”的场景:
i18n.t({ id: "Hello" });
i18n.t({ id: "msg.hello", message: "Hello" });
i18n.t({ id: "My name is {name}", values: { name: "Tom" } });
i18n.t({
id: "msg.name",
message: "My name is {name}",
comment: "Message showing the passed in name",
values: { name: "Tom" },
});
描述符结构与源码中的类型定义一致(i18n.ts#L65-L70):id、message?、comment?、values?。
查找、回退与 missing 处理
_ 方法的内部流程(i18n.ts#L212-L287)值得逐段看:
- 未激活 locale 时直接抛错,错误信息明确提示先调用
i18n.activate(locale),并指出可能源于初始化时序竞态; - 若传入的是描述符,则解出
values、message、id; - 查表同样使用
hasOwnProperty保护(防止"constructor"、"toString"这类 ID 解析到原型链成员); - 回退链为
目录翻译 → options.message(默认消息)→ 消息 ID 本身:
let translation = messageForId || message || id
- 若翻译缺失(
messageForId === undefined):- 配置了
missing处理器(字符串或(locale, id) => string函数)时,直接返回其结果并跳过事件——这是官方推荐的调试手段,例如setupI18n({ missing: "🚨" })或弹出提醒的函数形式; - 否则触发
missing事件,事件对象形如{ locale, id },供上层埋点或告警。
- 配置了
一个值得注意的执行顺序:missing 事件在未配置 missing 处理器时才发出;配置了处理器则以处理器返回值为准。
未编译消息的开发/生产差异
编译后的消息在运行时是 token 数组(形如 <a href="https://link.gitcode.com/i/9fa8cbf99bf3014b116e662c1f2feb23" target="_blank">"Ola!"]),而字符串形式的消息意味着“未编译”。源码中的处理([i18n.ts#L260-L276):
if (isString(translation)) {
if (this._messageCompiler) {
translation = this._messageCompiler(translation) // 即时编译
} else {
console.warn(`Uncompiled message detected! ...`) // 生产环境警告
}
}
- 开发环境:构造函数已自动注册
compileMessage(来自@lingui/message-utils/compileMessage),字符串消息会被即时编译,因此用裸目录开发体验完整; - 生产环境:默认没有编译器,遇到未编译消息只打印警告,ICU 插值、复数等特性对该消息失效——这也是官方反复强调“生产必须
lingui compile”的原因; - 如果确实需要生产环境运行时编译目录(如从服务端拉取未编译 JSON),可显式调用
i18n.setMessagesCompiler(compileMessage)注册编译器,代价是携带编译器进入 bundle。
宏入口 @lingui/core/macro:构建期替换 + 运行期哨兵
README 示例中的 t\Hello ${name}`` 并非运行时函数调用,而是构建期被转译掉的宏。宏入口文件 macro/index.mjs 揭示了其双重身份:
import babelPluginMacros from "babel-plugin-macros"
import { macro } from "@lingui/babel-plugin-lingui-macro/macro"
const { createMacro } = babelPluginMacros
export default createMacro(macro, {
configName: "lingui",
})
// the following shims for the case when this import used by nodejs code without transpilation
function printError() {
throw new Error(
`The macro you imported from "@lingui/core/macro" is being executed outside the context of compilation. ...`
)
}
export const t = printError
export const msg = printError
export const ph = printError
export const defineMessage = printError
export const plural = printError
export const select = printError
export const selectOrdinal = printError
三段信息量:
- 默认导出通过
babel-plugin-macros的createMacro把@lingui/babel-plugin-lingui-macro中的宏实现挂载进来,configName: "lingui"表示构建时会读取项目中名为lingui的宏配置段; - 具名导出(
t/msg/ph/defineMessage/plural/select/selectOrdinal)在正常构建中会被 Babel 插件在编译阶段整体替换为携带{ id, message, values, ... }的消息描述符,运行时根本不会执行到这些函数; - 这些具名导出同时是故障哨兵:如果构建链没配好(
babel-plugin-macros、@lingui/swc-plugin或babel-plugin-lingui-macro之一缺失),或者代码对宏入口做了动态import()(不支持),运行时调用会直接抛出带排障指引的错误,而不是静默失败。
再看 package.json 中的 ./macro 条件导出:browser 条件指向 macro/browser.mjs,其中所有导出是空函数,且模块顶层直接 throw 同样的错误——这保证任何绕过转译直接在浏览器执行的场景都能立即暴露配置问题,而不是渲染出错误文案。
因此,README 中“t 等宏在构建时被编译为 ICU 消息,需要 Babel 或 SWC 插件”这句话,从源码看即:宏入口 = 编译期宏注册 + 运行期报错 shim 的组合,二者缺一不可。宏的完整 API(含 defineMessage、ph、msg 的用法)见 宏参考文档。
格式化管线:interpolate 与 formats
消息查表完成后,真正执行 ICU 格式化的是 interpolate.ts。它的签名是柯里化的:
export function interpolate(
translation: CompiledMessage,
locale: string,
locales?: Locales,
) {
return (values: Values = {}, formats?: Formats): string => { ... }
}
i18n._ 的最后一步正是 interpolate(translation, this._locale, this._locales)(values, options?.formats)。
token 数组的递归展开
编译后的消息是一棵 token 树,formatMessage 用 reduce 展开:
- 字符串 token 直接拼接;
- 形如
[name, type, format]的数组 token 按type分发到对应格式化器;type为plural/selectordinal/select时,format是“分支名 → 子 token 树”的映射,先递归展开每个分支再交给格式化器选择; - 变量取值为
null/undefined时该 token 被跳过(返回已拼接的前缀); - 结果若含转义序列,会经
decodeEscapeSequences还原(escapeSequences.ts)。
内置格式化器(formats.ts)
getDefaultFormats(interpolate.ts#L18-L73)组装出六个格式化器:
| 类型 | 底层 API | 说明 |
|---|---|---|
plural |
Intl.PluralRules(cardinal) |
先查显式分支(=1 等),再按规则选择,最后兜底 other;支持 offset |
selectordinal |
Intl.PluralRules(ordinal) |
同上,序数规则 |
select |
— | 按变量值精确匹配分支,缺失时回退 other |
number |
Intl.NumberFormat |
支持格式名(查 formats 表)或直接传 options 对象 |
date |
Intl.DateTimeFormat |
支持 short/default/long/full 预设名或自定义 options |
time |
Intl.DateTimeFormat |
同上的时间变体 |
几个从源码可见的实现细节:
- locale 回退链:
normalizeLocales(formats.ts#L9-L12)会把locales(或当前locale)归一化为数组,并追加默认 locale"en"作为最终回退——即使浏览器缺少某语言的Intl数据,格式化也不会抛错; - 格式化器记忆化:所有
Intl.*Format/PluralRules实例通过getMemoized+ 全局Map按类型-locales-JSON(options)缓存,同一 locale + 同一格式只构造一次; - 复数中的
#:ICU 中#表示“偏移后的数值”。实现用占位符%__lingui_octothorpe__%在分支内标记#,选定分支后用当前value - offset的本地化数字替换(interpolate.ts#L30-L36); select的防护:分支值匹配同样走hasOwnProperty,防止"constructor"之类的运行值命中原型链而误选分支(interpolate.ts#L75-L81),未命中则落到other。
复数规则选择逻辑(formats.ts#L128-L147)是:
return rules[value] ?? rules[plurals.select(value - offset)] ?? rules.other
即显式 =value 分支 > Intl.PluralRules 规则分支 > other,与 ICU 语义一致。
事件系统:change 与 missing
I18n 继承自 eventEmitter.ts 中的轻量事件基类(32 行,基于 Set 存储监听器,on 返回取消订阅函数,emit 前先拷贝监听器数组以避免回调中增删监听器的迭代问题)。I18n 只声明了两个类型化事件(i18n.ts#L86-L89):
type Events = {
change: () => void
missing: (event: MissingMessageEvent) => void
}
change:在load与activate成功后触发,无参数。它是所有“语言切换后同步状态”逻辑的官方挂点;missing:当t请求的翻译在激活 locale 的目录中不存在(且未配置missing处理器)时触发,携带{ locale, id }:
i18n.on("missing", (event) => {
alert(`Translation in ${event.locale} for ${event.id} is missing!`)
})
注意 on 返回取消函数:const off = i18n.on("change", cb),之后 off() 即可解绑。
已废弃的辅助方法:i18n.date 与 i18n.number
I18n 上保留了 date 与 number 两个实例方法(i18n.ts#L294-L309),但源码注释已明确标记 @deprecated,官方建议直接使用原生 API:
new Intl.DateTimeFormat(i18n.locale, format).format(d)
new Intl.NumberFormat(i18n.locale, format).format(value)
它们的行为等价于 date(this._locales || this._locale, value, format),其中 locales 优先取备选列表。参考文档保留了完整示例(如 i18n.number(12345.678, { style: "currency", currency: "USD" }) 返回 $12,345.68),新代码应优先使用 Intl 原生构造器;这两个方法在消息插值内部({var, number} 等)仍由 formats 模块使用,废弃仅针对公开实例方法。
类型层:Register 接口与类型化消息 ID
对 TypeScript 用户,@lingui/core 预留了模块增强入口(i18n.ts#L36-L63):
// src/lingui.d.ts
import type enMessages from "./locales/en/messages.json";
declare module "@lingui/core" {
interface Register {
messageIds: keyof typeof enMessages;
}
}
MessageId 类型会据此解析为具体 ID 联合类型;未增强时回退为 string:
export type MessageId = Register extends {
messageIds: infer TIds extends string
} ? TIds : string
由此 i18n.t 的第一个参数与 MessageDescriptor.id 都获得“拼错 ID 即类型报错”的保护。仓库中 typetests/typed-ids 目录下的类型测试即用于验证该机制,类型测试入口见 tsconfig.json。
API 速查表
汇总 @lingui/core(版本 6.9.0,Node 开发要求 >=22.19.0,见 package.json)对外 API:
| API | 签名/类型 | 说明 |
|---|---|---|
i18n |
I18n 单例 |
模块默认实例,来自 setupI18n() |
setupI18n |
(params?: I18nProps) => I18n |
创建独立实例(需配合 runtimeConfigModule) |
i18n.load |
(locale, messages) 或 (allMessages) |
加载目录,重复加载按 Object.assign 合并 |
i18n.loadAndActivate |
({ locale, locales?, messages }) |
覆盖目录并立即激活 |
i18n.activate |
(locale, locales?) |
切换激活 locale,触发 change |
i18n.t / i18n._ |
(id, values?, options?) 或 (descriptor) |
翻译 + ICU 格式化;t 是 _ 的别名 |
i18n.setMessagesCompiler |
(compiler: MessageCompiler) |
启用运行时编译未编译目录 |
i18n.date / i18n.number |
已废弃 | 建议改用 Intl.DateTimeFormat / Intl.NumberFormat |
i18n.locale / locales / messages |
只读 getter | 当前激活状态 |
i18n.on |
("change" | "missing", cb) => off |
事件订阅,返回取消函数 |
formats |
命名空间 | date/time/number/plural 底层工具(内部使用) |
| 类型 | MessageId、Messages、AllMessages、Formats、Values、Register 等 |
见 i18n.ts 类型区 |
小结:编译期目录 + 轻量运行时的设计闭环
回到 README 的核心主张,@lingui/core 的“小”来自一条完整的设计闭环,且每一环都能在源码中找到对应:
- 消息提取与预编译前移到构建期——
lingui extract/lingui compile(@lingui/cli)把 ICU 消息编译为 token 数组,运行时因此不需要 MessageFormat 解析器; - 运行时只做查表、选分支、拼
Intl结果——interpolate.ts + formats.ts 全部建立在Intl.PluralRules/NumberFormat/DateTimeFormat之上,并带记忆化缓存; - 宏入口只做构建期替换——macro/index.mjs 的具名导出是故障哨兵而非真实 API;
- 开发体验与生产体积解耦——未编译目录只在开发环境即时编译,生产默认剔除编译器。
若你在使用中遇到问题,建议的排查顺序是:先确认目录已编译(生产环境未编译消息会打印 Uncompiled message detected! 警告)→ 确认 activate 先于任何 t 调用执行(否则直接抛错)→ 用 missing 事件或 missing 处理器定位缺失翻译 → 检查宏构建链(Babel/SWC 插件)是否生效。更细的 API 语义可继续参考 核心 API 参考文档 与 宏参考文档。