js-lingui @lingui/core 运行时 API 详解:i18n 对象、目录加载与消息格式化
js-lingui @lingui/core 运行时 API 详解:i18n 对象、目录加载与消息格式化
@lingui/core 是 js-lingui 的 i18n 运行时内核,负责管理消息目录(message catalogs)、当前激活的语言环境(locale),以及消息的翻译与格式化。本文基于官方参考文档 website/docs/ref/core.md 并结合 packages/core 的源码实现,完整讲解全局 i18n 实例、I18n 类的全部公开方法、setupI18n 工厂函数、AllMessages/Messages 类型、事件机制,以及编译消息(compiled message)与运行时解释执行的底层链路,帮助你在任何 JavaScript/TypeScript 项目中正确加载目录、切换语言并格式化 ICU MessageFormat 消息。
安装与包概览
npm install --save @lingui/core
当前仓库中 @lingui/core 的版本为 6.9.0,见 packages/core/package.json。几个与使用直接相关的包级事实:
- 纯 ESM 包(
"type": "module",主入口为dist/index.mjs),且声明"sideEffects": false,便于打包器做 tree-shaking; - 运行时依赖只有
@lingui/message-utils(提供消息编译能力)与@lingui/babel-plugin-lingui-macro,Node 要求>=22.19.0(见 package.json 的engines字段),因此本文示例均以现代 ESM 环境为前提; - 包对外导出核心对象
i18n(全局单例)、setupI18n工厂函数与I18n类,见 packages/core/src/index.ts。
@lingui/core 提供的是一个全局单例的 i18n 对象,你可以直接导入使用:
import { i18n } from "@lingui/core";
/**
* Load messages for the requested locale and activate it.
* This function isn't part of the Lingui because there are
* many ways how to load messages — from REST API, from file, from cache, etc.
*/
async function activate(locale: string) {
const { messages } = await import(`${locale}/messages.js`);
i18n.loadAndActivate({ locale, messages });
}
activate("cs");
// returns the Czech translation of "Hello World"
const translation = i18n.t("Hello World");
从源码看,全局单例就是在模块加载时执行一次 setupI18n() 得到的,见 packages/core/src/index.ts#L14-L16:
// Default i18n object
import { setupI18n } from "./i18n"
export const i18n = setupI18n()
如果你不想用这个全局实例,也可以自行调用 setupI18n](#setupi18noptions) 创建独立实例;但此时需要同时配置 [runtimeConfigModule,否则宏(macro)仍然会引用默认的全局 i18n。
类 I18n:目录加载与语言激活
I18n 类继承自内部的事件发射器 EventEmitter(见 packages/core/src/eventEmitter.ts),核心状态维护在私有字段 _locale、_locales、_messages、_missing、_messageCompiler 中,定义于 packages/core/src/i18n.ts#L102-L121。
i18n.loadAndActivate(options)
options 参数是包含以下属性的对象:
locale:初始激活的语言环境;locales:备选语言环境列表(BCP-47 语言标签),用于数字和日期格式化(有些国家存在多种数字/日期格式);messages:已编译的消息目录。
它允许为给定语言设置(覆盖)目录并激活该语言:
import { i18n } from "@lingui/core";
const { messages } = await import(`${locale}/messages.js`);
i18n.loadAndActivate({ locale, messages });
对应源码实现在 packages/core/src/i18n.ts#L190-L197:该方法直接赋值 _locale/_locales 并整体覆盖该语言的目录(注意与 load 的合并语义不同),最后触发 change 事件。
i18n.load(allMessages) 与 i18n.load(locale, messages)
两种重载形式:一次性加载多个语言目录,或为单个语言加载目录。当某语言的目录已经加载过时,再次调用 i18n.load 会按 Object.assign 将新消息合并进已有目录:
import { i18n } from "@lingui/core";
/**
* This is just an example of what the catalog looks like internally.
* Formatting of string messages only works in development. See note below.
*/
const messagesEn = {
Hello: "Hello",
"Good bye": "Good bye",
"My name is {name}": "My name is {name}",
};
const messagesCs = {
Hello: "Ahoj",
"Good bye": "Nashledanou",
"My name is {name}": "Jmenuji se {name}",
};
// highlight-start
i18n.load({
en: messagesEn,
cs: messagesCs,
});
// highlight-end
// This is the same as loading message catalogs separately per language:
// i18n.load('en', messagesEn)
// i18n.load('cs', messagesCs)
提示:不要手写目录。上面只是目录的内部结构示例。真实应用中,消息来自
lingui compile命令生成的外部目录文件,或由 Vite Plugin、Webpack Loader、Metro Transformer 等工具在构建时编译生成。字符串形式的消息格式化(如
"My name is {name}")只在开发模式下有效——此时消息会被即时解析;而在生产模式下,消息必须已经过lingui compile编译。
真实应用中同一示例的写法:
import { i18n } from "@lingui/core";
// File generated by `lingui compile`
import { messages as messagesEn } from "./locale/en/messages.js";
i18n.load("en", messagesEn);
从源码看(packages/core/src/i18n.ts#L153-L185),重载判定依据是第一个参数是否为字符串:load('en', catalog) 走单语言分支,其余情况按 AllMessages 遍历每个语言调用私有方法 _load;_load 内部先查已有目录再决定“新建”还是 Object.assign 合并,并且使用 hasOwnProperty 做自有属性检查,防止以 __proto__ 等原型键作为 locale 时发生原型污染。两次重载都会触发 change 事件。
i18n.setMessagesCompiler(compiler)
注册一个 MessageCompiler,使未编译的目录可以在运行时使用。生产构建中通常会剔除该编译器以减小包体积。
默认情况下,消息目录应在构建期预先编译。但如果你确实需要在运行时编译目录,可以用该方法设置编译器:
import { compileMessage } from "@lingui/message-utils/compileMessage";
i18n.setMessagesCompiler(compileMessage);
这一点在构造函数中有直接体现:开发环境下 I18n 会自动注册仓库自带的 compileMessage(packages/core/src/i18n.ts#L109-L114):
constructor(params: I18nProps) {
super()
if (process.env.NODE_ENV !== "production") {
this.setMessagesCompiler(compileMessage)
}
...
}
这正是前文“字符串目录只在开发模式可格式化”的原因:生产环境若不手动注册编译器,遇到未编译的字符串消息只会打印告警而不做 ICU 解析(i18n.ts#L262-L276)。compileMessage 本身基于 @messageformat/parser 将 ICU MessageFormat 解析为编译消息结构,实现见 packages/message-utils/src/compileMessage.ts。
i18n.activate(locale[, locales])
激活指定语言及其备选语言。调用之后,i18n.t 将返回该激活语言的消息:
import { i18n } from "@lingui/core";
i18n.activate("en");
i18n.t("Hello"); // Return "Hello" in English
i18n.activate("cs");
i18n.t("Hello"); // Return "Hello" in Czech
从源码看,activate 在开发环境下会检查目标语言的目录是否已加载,未加载时输出 Messages for locale "..." not loaded. 的警告,然后更新 _locale/_locales 并触发 change 事件(i18n.ts#L199-L209)。
翻译与格式化:i18n.t 与 i18n._
i18n.t(messageId[, values[, options]])
翻译与格式化消息的核心方法,参数:
messageId:在目录中标识消息的唯一消息 ID;values:包含消息中使用的变量的对象;options.message:默认译文(可选)。主要在不使用自然语言消息 ID 的应用中(例如msg.id、Component.title);options.formats:自定义的日期/时间格式定义(可选)。键为格式名,值为Intl.DateTimeFormatOptions或Intl.NumberFormatOptions。
import { i18n } from "@lingui/core";
// Simple message
i18n.t("Hello");
// Message with variables
i18n.t("My name is {name}", { name: "Tom" });
// Message with custom messageId
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");
// Short date format
i18n.t("It starts on {someDate, date, short}", { someDate: date });
// Short time format
i18n.t("It starts on {someTime, time, short}", { someTime: time });
// Date skeleton format
i18n.t("It starts on {someDate, date, ::GrMMMdd}", { someDate: date });
// Custom date format
i18n.t("It starts on {someDate, date, myStyle}", { someDate: date }, { formats: { myStyle: { day: "numeric" } } });
几个从源码确认的行为细节(packages/core/src/i18n.ts#L214-L287):
- 必须先激活语言。若未设置 locale 就调用翻译,会抛出明确错误,提示先调用
i18n.activate(locale); - 三级回退链:
翻译结果 = 目录命中 || options.message || messageId(i18n.ts#L258),即目录查不到时依次退回默认译文、最后退回 ID 本身; - 解析顺序:编译消息(数组形式)交给 interpolate 执行变量插值与 ICU 格式化(
plural/select/number/date/time等);纯字符串结果则检查转义序列后原样返回。
i18n.t(messageDescriptor)
messageDescriptor 是包含消息 ID、默认消息及其他参数的对象,适合“先声明消息、后使用”的场景:
import { i18n } from "@lingui/core";
// Simple message
i18n.t({ id: "Hello" });
// Simple message using custom ID
i18n.t({ id: "msg.hello", message: "Hello" });
// Message with variable
i18n.t({ id: "My name is {name}", values: { name: "Tom" } });
// Message with comment, custom ID and variable
i18n.t({
id: "msg.name",
message: "My name is {name}",
comment: "Message showing the passed in name",
values: { name: "Tom" },
});
更多细节可参考 Message Descriptor。对应的 MessageDescriptor 类型在 i18n.ts#L65-L70 中定义:{ id, comment?, message?, values? }。
i18n._(...)
规范(canonical)的翻译方法,i18n.t 只是它的别名:
import { i18n } from "@lingui/core";
i18n._({ id: "Hello" });
从源码看,别名关系是一个显式绑定(i18n.ts#L289-L292):
/**
* @see I18n._
*/
t: I18n["_"] = this._.bind(this)
日期与数字格式化(已废弃)
i18n.date(value[, format])
按当前激活语言的惯例格式格式化日期。
value:要格式化的日期,接受Intl.DateTimeFormat.prototype.format支持的取值;若为字符串,会先用new Date(date)构造Date对象;format:可选,会作为Intl.DateTimeFormat构造函数的options参数传入,用于自定义日期格式。
废弃提示:
i18n.date将被移除。建议直接使用Intl.DateTimeFormat:new Intl.DateTimeFormat(i18n.locale, format).format(d);
import { i18n } from "@lingui/core";
const d = new Date("2021-07-23T16:23:00");
i18n.activate("en");
i18n.date(d);
// Returns "7/23/2021"
i18n.date(d, { timeStyle: "medium" });
// Returns "4:23:00 PM"
i18n.date(d, { dateStyle: "medium", timeStyle: "medium" });
// Returns "Jul 23, 2021, 4:23:00 PM"
i18n.activate("cs");
i18n.date(d);
// Returns "23. 7. 2021"
i18n.number(value[, format])
按当前激活语言的惯例格式格式化数字。
value:要格式化的数字,接受Intl.NumberFormat.prototype.format支持的取值;format:可选,会作为Intl.NumberFormat构造函数的options参数传入,用于自定义数字格式。
废弃提示:
i18n.number将被移除。建议直接使用Intl.NumberFormat:new Intl.NumberFormat(i18n.locale, format).format(value);
import { i18n } from "@lingui/core";
i18n.activate("en");
i18n.number(12345.678);
// Returns "12,345.678"
i18n.number(12345.678, { style: "currency", currency: "USD" });
// Returns "$12,345.68"
i18n.activate("cs");
i18n.number(12345.678);
// Returns "12 345,678"
i18n.number(12345.678, { style: "currency", currency: "CZK" });
// Returns "12 345,68 Kč"
从源码看,两个方法都带有 @deprecated 标记(i18n.ts#L294-L309),底层实现在 packages/core/src/formats.ts。其中有两点值得注意:
Intl格式化器实例按「类型 + locales + options」做记忆化缓存(formats.ts#L4-L12、L149-L165),同一 locale 与格式的重复调用不会重复构造对象;- locale 列表会被
normalizeLocales追加一个兜底的defaultLocale = "en"(formats.ts#L7),保证即使locales配置不规范,Intl构造也不会失败。复数规则(plural)则基于Intl.PluralRules并支持offset(formats.ts#L128-L147)。
setupI18n([options])
初始化并返回一个新的 I18n 实例。通常你只需调用一次,然后在整个代码库中复用返回的 i18n 对象。
大多数情况下你无需自建
i18n实例,直接使用@lingui/core导出的全局对象即可。若确实需要自建,请记得配置runtimeConfigModule,保证宏正常工作。
import { setupI18n } from "@lingui/core";
const i18n = setupI18n();
工厂函数接受可选的 options 参数,用于设置 i18n 实例的初始状态:
options.locale
初始激活的语言环境:
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({ locale: "en" });
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.activate("en")
options.locales
备选语言环境列表(BCP-47 语言标签),用于数字和日期格式化(某些国家使用多种数字/日期格式)。未设置时使用当前激活语言:
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({
locale: "ar",
locales: ["en-UK", "ar-AS"],
});
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.activate("ar", ["en-UK", "ar-AS"])
options.messages
初始 Messages:
import { setupI18n } from "@lingui/core";
const messages = {
en: require("./locale/en/messages").messages, // your path to compiled messages here
cs: require("./locale/cs/messages").messages, // your path to compiled messages here
};
const i18n = setupI18n({ messages });
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.load(messages)
options.missing
当翻译缺失时返回的自定义消息,适合调试场景:
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({ missing: "🚨" });
i18n.t("missing translation") === "🚨"; // Returns the custom missing message
也可以传入一个接收激活 locale 和消息 ID 的函数:
import { setupI18n } from "@lingui/core";
function missing(locale, id) {
alert(`Translation in ${locale} for ${id} is missing!`);
return id;
}
const i18n = setupI18n({ missing });
i18n.t("missing translation"); // Triggers an alert
构造函数如何处理这些选项,可对照 i18n.ts#L109-L121:missing 存入 _missing,messages 走 load(),locale/locales 走 activate()(locale 未给出时回退到 defaultLocale,即 en)。missing 的字符串/函数两种形态在翻译路径中被检查:命中缺失且配置了 missing 时优先返回它,否则触发 missing 事件(i18n.ts#L248-L256)。
类型:AllMessages 与 Messages
I18n.load 方法中的 AllMessages 参数类型为:
type AllMessages = { [locale: string]: CompiledMessage };
// Example
const messages: AllMessages = {
en: {
messages: {
Hello: "Hello",
"Good bye": "Good bye",
},
},
cs: {
messages: {
Hello: "Ahoj",
"Good bye": "Nashledanou",
},
},
};
Messages 是 AllMessages 中每个语言的类型:消息 ID 到该语言译文的映射;当消息已编译时,值也可以是函数(编译产物为可执行数组/函数形式):
type Messages = { [messageId: string]: string | Function };
// Example
const messagesEn: Messages = {
Hello: "Hello",
"Good bye": "Good bye",
};
源码中的类型定义在 i18n.ts#L29-L34:Messages = Record<string, UncompiledMessage | CompiledMessage>,AllMessages = Record<Locale, Messages>,其中 UncompiledMessage 即 ICU 字符串。
另外,MessageId 通过空的 Register 接口支持模块增强(i18n.ts#L36-L63):在 .d.ts 中通过 declare module "@lingui/core" 给 Register 注入 messageIds,即可把 i18n.t 的消息 ID 收窄为编译期联合类型,获得消息 ID 的 IDE 补全与拼写检查。
事件:change 与 missing
change
在切换语言或加载新目录之后触发,不携带任何参数。触发点即 load、loadAndActivate、activate 末尾的 this.emit("change")(见上文源码引用)。
missing
当 i18n.t 请求的消息在当前激活语言的目录中不存在时触发,事件携带 locale 与缺失的消息 ID:
i18n.on("missing", (event) => {
alert(`Translation in ${event.locale} for ${event.id} is missing!`);
});
事件机制由内部的泛型 EventEmitter 提供(packages/core/src/eventEmitter.ts)。一个实用细节:on() 返回一个取消订阅函数,方便在组件卸载等场景清理监听(eventEmitter.ts#L8-L13):
const off = i18n.on("missing", (event) => { /* ... */ });
// 不再需要时
off();
事件载荷类型 MissingMessageEvent 为 { locale, id },定义见 i18n.ts#L72-L89。相关行为在 packages/core/src/i18n.test.ts 与 packages/core/src/eventEmitter.test.ts 中有测试覆盖。
底层链路:从编译消息到最终输出
把前面的 API 串起来,一次 i18n.t("...") 的完整链路是:
- 编译期(构建时):
lingui compile或 Vite Plugin / Webpack Loader / Metro Transformer 调用compileMessage(packages/message-utils/src/compileMessage.ts#L99-L109),用@messageformat/parser把 ICU MessageFormat 字符串解析为编译消息——CompiledMessage是一个 token 数组,普通文本为字符串 token,插值/复数/选择等结构为[name, type, format]三元组(compileMessage.ts#L12-L20),日期 skeleton(如::GrMMMdd)在编译期就被解析为Intl.DateTimeFormatOptions; - 加载期(运行时):
i18n.load/loadAndActivate把编译后的目录按 locale 存入_messages,并触发change; - 翻译期:
i18n._先做缺失检查与missing处理,再按「编译消息为数组、字符串则需运行时编译」区分两条路径(i18n.ts#L258-L287),最终调用 interpolate 递归遍历 token,对plural/selectordinal/select递归解释各分支(含#octothorpe 替换与offset处理),对number/date/time调用带缓存的Intl格式化器,并对最终结果做转义序列解码。
这条链路也解释了文档中的一条重要约定:开发模式下字符串目录可用(自动注册了 compileMessage),生产模式必须使用编译后的目录,否则 ICU 插值与复数功能会失效,仅能回退输出原文(并伴随控制台告警)。
自建 i18n 实例与宏的配合
若你使用 setupI18n 创建了自己的 i18n 实例,还需要告诉宏该从哪里导入 i18n:在 Lingui 配置中设置 runtimeConfigModule(默认值 <a href="https://link.gitcode.com/i/5804fef533c338d850c4a96550c21ea6" target="_blank">"@lingui/core", "i18n"],见 [website/docs/ref/conf.md#L511-L529):
{
"runtimeConfigModule": ["./custom-i18n-config", "i18n"]
}
该配置值会成为每个被转换文件中的实际 import 语句,因此应使用模块路径而非相对路径。
小结与延伸阅读
@lingui/core 的 API 面很小但语义完整:
- 加载:
load(合并)与loadAndActivate(覆盖并激活); - 翻译:
i18n.t/i18n._,支持 ID 字符串与消息描述对象两种形式,缺失时有missing处理器与missing事件双通道; - 状态通知:
change事件,on()返回取消订阅函数; - 格式化:
i18n.date/i18n.number已废弃,建议直接使用Intl.DateTimeFormat/Intl.NumberFormat。
仓库中可进一步深入的材料:
- 运行时源码:packages/core/src/i18n.ts、packages/core/src/interpolate.ts、packages/core/src/formats.ts;
- 行为测试:packages/core/src/i18n.test.ts、packages/core/src/eventEmitter.test.ts;
- 消息编译实现:packages/message-utils/src/compileMessage.ts;
- 文档交叉引用:CLI(lingui compile)、Lingui 配置(runtimeConfigModule)、Vite Plugin、Webpack Loader、Metro Transformer;
- 完整可运行的示例工程:examples/js。