@gravity-ui/i18n

中文文档
1.8.0发布于 2025/04/08MITTypeScriptESM + CJS零依赖近 30 天下载 10.7万

i18n 重力 UI 服务库

中文使用文档
文档目录8 节
  1. I18N公用事业
  2. 安装
  3. API 密码
  4. 使用示例
  5. 温和
  6. 多元化
  7. 缠绕
  8. 键入

@gravity-ui/i18n ! (简体中文) npm package CI

I18N公用事业

I18N套装中的公用事业是为重力UI服务的国际化而设计的.

安装

npm install --save @gravity-ui/i18n

API 密码

构造器( 选项)

接受 options 可选对象 logger 用于记录库警告.

日志

Logger 应该有明确的 log 使用下列签名的方法:

  • message - 将会被记录的信息串
  • options - 记录选项的对象:
    • level - 记录信息级别,总是 'info'
    • logger - 在哪里登录图书馆信件
    • extra - 附加选项对象,带有单个 type 弦,这总是 i18n

使用示例

keysets/en.json

{
  "wizard": {
    "label_error-widget-no-access": "No access to the chart"
  }
}

keysets/ru.json

{
  "wizard": {
    "label_error-widget-no-access": "Нет доступа к чарту"
  }
}

index.js

const ru = require('./keysets/ru.json');
const en = require('./keysets/en.json');

const {I18N} = require('@gravity-ui/i18n');

const i18n = new I18N();
i18n.registerKeysets('ru', ru);
i18n.registerKeysets('en', en);

i18n.setLang('ru');
console.log(
    i18n.i18n('wizard', 'label_error-widget-no-access')
); // -> "Нет доступа к чарту"

i18n.setLang('en');
console.log(
    i18n.i18n('wizard', 'label_error-widget-no-access')
); // -> "No access to the chart

// Keyset allows for a simpler translations retrieval
const keyset = i18n.keyset('wizard');
console.log(
    keyset('label_error-widget-no-access')
); // -> "No access to the chart"


i18n.setLang('ru');
console.log(
    keyset('label_error-widget-no-access')
); // -> "Нет доступа к чарту"

// Checking if keyset has a key
if (i18n.has('wizard', 'label_error-widget-no-access')) {
    i18n.i18n('wizard', 'label_error-widget-no-access')
}

温和

图书馆支持调温. 被模板化的变量被双曲括号所包围,这些值被传递到i18n函数作为密钥值词典:

keysets.json

{
  "label_template": "No matches found for '{{inputValue}}' in '{{folderName}}'"
}

index.js

i18n('label_template', {inputValue: 'something', folderName: 'somewhere'});  // => No matches found for "something" in "somewhere"

多元化

多元化可用于对依赖于数值的密钥进行简单本地化. 当前库用途 多元规则 通过 内通. 多规则 API。 。 。 .

你也许需要 多边填充 页:1 内通. 多元规则 API 如果在浏览器中不可用.

有6个复数形式(见 已解决选项:

  • 0 (即使语言中不支持窗体,在计数=0时也会使用)
  • 一个( 单边)
  • 两人(双人)
  • 少 (弹匣)
  • 许多(如果分数有单独的类别,也用于分数)
  • 其他(所有语言所需的形式——一般复数形式——如果语言只有单一形式,也使用)

实例 keysets.json 有复数密钥

{
  "label_seconds": {
    "one": "{{count}} second is left",
    "other":"{{count}} seconds are left",
    "zero": "No time left"
  }
}

联合来文的使用

i18n('label_seconds', {count: 1});  // => 1 second
i18n('label_seconds', {count: 3});  // => 3 seconds
i18n('label_seconds', {count: 7});  // => 7 seconds
i18n('label_seconds', {count: 10}); // => 10 seconds
i18n('label_seconds', {count: 0});  // => No time left

[过期] 旧复数格式

旧格式将在v2中被删除.

{
  "label_seconds": ["{{count}} second is left", "{{count}} seconds are left", "{{count}} seconds are left", "No time left"]
}

复数键包含 4 个值,每个 QQ 对应 a PluralForm 符号值 。 enum值为: One, (中文(简体) ), Few, (中文(简体) ), Many,以及 None分别是: 复数化的模板变量名是 count。 。 。 .

[已失效] 自定义复数化

由于每种语言都有自己的多元化方式,库提供一种方法来配置任何所选语言的规则.

配置函数接受以语言为键的对象,而复数化函数作为值.

复数函数接受数字和 PluralForm enum,并预计将根据提供的数字返回一个enum值.

const {I18N} = require('@gravity-ui/i18n');

const i18n = new I18N();

i18n.configurePluralization({
  en: (count, pluralForms) => {
    if (!count) return pluralForms.None;
    if (count === 1) return pluralForms.One;
    return pluralForms.Many;
  },
});

[过期] 提供复数化规则

框外支持的两种语言为英语和俄语.

联合国

语言密钥 : en。 。 。 .

  • One 对应于1和-1.
  • Few 未使用.
  • Many 对应除 0外的任何其他数字.
  • None 对应于 0.
俄语

语言密钥 : ru。 。 。 .

  • One 对应于1中结束的任意数字,但±11除外.
  • Few 对应以2、3或4结尾的任何数字,但±12、±13和±14除外.
  • Many 对应除 0外的任何其他数字.
  • None 对应于 0.
默认

默认情况下使用英语规则,用于任何没有被配置的复数化功能的语言.

缠绕

最大巢穴深度有限 - 只有1级(用于词汇表)

Nesting允许您在翻译中引用其他密钥. 汇编术语可能有用.

基础

密钥

{
  "nesting1": "1 $t{nesting2}",
  "nesting2": "2",
}

样本

i18n('nesting1'); // -> "1 2"

您可以通过预置密钥集引用其他密钥集Name :

// global/en.json
{
  "app": "App"
}

// service/en.json
{
  "app-service": "$t{global::app} service"
}

键入

键入 i18nInstance.i18n 函数,遵循步骤:

筹备

准备一个 JSON 密钥集文件, 这样打字程序就可以获取数据 。 获取密钥时, 添加创建附加 data.json 文档。 要减少文件大小并加快 IDE 解析速度, 您可以用 'str'。 。 。 .

async function createFiles(keysets: Record<Lang, LangKeysets>) {
    await mkdirp(DEST_PATH);

    const createFilePromises = Object.keys(keysets).map((lang) => {
        const keysetsJSON = JSON.stringify(keysets[lang as Lang], null, 4);
        const content = umdTemplate(keysetsJSON);
        const hash = getContentHash(content);
        const filePath = path.resolve(DEST_PATH, `${lang}.${hash.slice(0, 8)}.js`);

        // <New lines>
        let typesPromise;

        if (lang === 'ru') {
            const keyset = keysets[lang as Lang];
            Object.keys(keyset).forEach((keysetName) => {
                const keyPhrases = keyset[keysetName];
                Object.keys(keyPhrases).forEach((keyName) => {
                    // mutate object!
                    keyPhrases[keyName] = 'str';
                });
            });

            const JSONForTypes = JSON.stringify(keyset, null, 4);
            typesPromise = writeFile(path.resolve(DEST_PATH, `data.json`), JSONForTypes, 'utf-8');
        }
        // </New lines>

        return Promise.all([typesPromise, writeFile(filePath, content, 'utf-8')]);
    });

    await Promise.all(createFilePromises);
}

连接

在你身边 ui/utils/i18n 目录(在配置i18n并导出它供所有接口使用的地方),导入打字功能 I18NFn 还有你的 Keysets。在您的 i18n 配置完成后,返回已设定的函数

import {I18NFn} from '@gravity-ui/i18n';
// This must be a typed import!
import type Keysets from '../../../dist/public/build/i18n/data.json';

const i18nInstance = new I18N();
type TypedI18n = I18NFn<typeof Keysets>;
// ...
export const ci18n = (i18nInstance.i18n as TypedI18n).bind(i18nInstance, 'common');
export const cui18n = (i18nInstance.i18n as TypedI18n).bind(i18nInstance, 'common.units');
export const i18n = i18nInstance.i18n.bind(i18nInstance) as TypedI18n;

其他问题

打字逻辑

有几个打字用例:

  • 调用按键作为字符串字符串传递的函数
i18n('common', 'label_subnet'); // ok
i18n('dcommon', 'label_dsubnet'); // error: Argument of type '"dcommon"' is not assignable to parameter of type ...
i18n('common', 'label_dsubnet'); // error: Argument of type '"label_dsubnet"' is not assignable to parameter of type ...
  • 调用一个函数, 将无法转换成字串的字符串传递给它( 如果 ts 无法得出字符串类型, 它不会丢出错误 )
const someUncomputebleString = `label_random-index-${Math.floor(Math.random() * 4)}`;
i18n('some_service', someUncomputebleString); // ok

for (let i = 0; i < 4; i++) {
    i18n('some_service', `label_random-index-${i}`); // ok
}
  • 调用函数, 传递到可以转换为字元的字符串
const labelColors = ['red', 'green', 'yelllow', 'white'] as const;
for (let i = 0; i < 4; i++) {
    i18n('some_service', `label_color-${labelColors[i]}`); // ok
}

const labelWrongColors = ['red', 'not-existing', 'yelllow', 'white'] as const;
for (let i = 0; i < 4; i++) {
    i18n('some_service', `label_color-${labelWrongColors[i]}`); // error: Argument of type '"not-existing"' is not assignable to parameter of type ...
}

为何不支持通过类打字

这个函数可以打破或使一些i18n的情景复杂化,所以被添加为函数扩展. 如果证明有效,我们可能会把它加入一个类别,以避免铸出输出的功能.

为什么内置方法可能失败

使用已打入的内置函数方法实施嵌入式结构和有条件类型的穿行是一个足够复杂的任务. 这就是为什么打字只有在使用直接函数呼叫和 bind 调用到第三个参数.

为什么我不能直接生成 ts 文件来输入密钥值?

你可以通过将结果类型传递到I18NFn来做到这一点. 然而,由于文件大小大,ts开始消耗大量资源,使IDE大幅减速,但JSON文件却并非如此.

为什么I18N级的其他方法没有被打入?

他们可以打字,我们将感激 如果你帮助执行它。 情况是,在1%的案件中使用了其他方法.

版本与发布记录

@gravity-ui/i18n 共发布 10 个版本,首次发布于 2022/09/08;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.8.0latest2025/04/081.6 年前
1.7.02024/11/182 年前
1.6.02024/07/122 年前
1.5.12024/05/202 年前
1.5.02024/05/042 年前
1.4.02024/03/222 年前

关于 @gravity-ui/i18n 的常见问题

@gravity-ui/i18n 是什么?

i18n 重力 UI 服务库

如何安装 @gravity-ui/i18n?

在项目目录运行 npm install @gravity-ui/i18n,或使用 pnpm add / yarn add / bun add。

@gravity-ui/i18n 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gravity-ui/i18n 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gravity-ui/i18n 可以商用吗?

@gravity-ui/i18n 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gravity-ui/i18n 的下载量有多少?

根据 npm 官方下载统计,@gravity-ui/i18n 在 2026/10/17 – 2026/11/15 这 30 天内被下载 106,928 次,日均约 3,564 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gravity-ui/i18n 还在维护吗?

最新版本 1.8.0 发布于 2025/04/08(1.6 年前);至今共发布 10 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/09/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。