@fiverr/i18n

中文文档
1.9.2发布于 2024/11/05MITCommonJS近 30 天下载 4495

Translation helper

原始使用文档
文档目录13 节
  1. Usage
  2. Translate
  3. Find alternatives
  4. Handle missing
  5. Add more translations after instantiation
  6. Features
  7. Interpolate with data
  8. One/other
  9. Instance with a scope
  10. Scoped child instance
  11. Instance
  12. Singleton (i18n)
  13. Helper functions

i18n

Isomorphic translation engine. Mimics Rails' i18n interface.

Usage

const I18n = require('@fiverr/i18n');
const translations = require('./translations.json');

const i18n = new I18n({translations});
OptionTypeDescription
translationsObjectRepresentation of translation structure Must be JSON compliant otherwise will be treated like an empty object
missingFunctionCall this function when a key is missing. Function accepts arguments: key, scope, translations_object
emptyFunctionCall this function when a value is empty. Function accepts arguments: key, value, scope, translations_object
$scopeStringOmittable prefix. see Scope The base is translations key root
const i18n = new I18n({
    translations: {...},
    missing: key => logMissingKeyEvent({key: `missing_translation.${key.replace(/\W/g, '_')}`}),
    empty: key => logEmptyValueEvent({key: `empty_translation.${key.replace(/\W/g, '_')}`}),
    $scope: 'my_app.en'
});

Translate

i18n.t('my.key'); // I'm a sentence

Find alternatives

i18n.t(['my.missing.key', 'my.key']); // I'm a sentence

Handle missing

By default, missing keys or empty values return the last part of the key

i18n.t('this.is.a.missing_key'); // missing key

But returning a truthy value from 'missing' and 'empty' callbacks will allow a custom fallback

const i18n = new I18n({
    translations: {...},
    empty: (key, value, scope) => {
        if (scope.startsWith('en-US')) {
            return; // default fallback
        }
        return i18n.t(key, { $scope: 'en-US' }); // Try English
    },
    $scope: 'en-US'
});

Add more translations after instantiation

i18n.add({yet: {another: {key: 'I\'m here, too!'}}});
Use:
i18n.translate('yet.another.key'); // I'm here, too!
Or:
i18n.t('yet.another.key'); // I'm here, too!

Features

Interpolate with data

const i18n = new I18n({
    translations: {
        my: { string: 'a dynamic %{thing} in a static string' }
    }
});
i18n.t('my.string', {thing: 'value'}); // a dynamic value in a static string

One/other

const i18n = new I18n({
    translations: {
        it_will_take_me_days: {
            one: 'It\'ll take me one day',
            other: 'It\'ll take me %{count} days'
        }
    }
});
i18n.t('it_will_take_me_days', {count: 1}); // It'll take me one day
i18n.t('it_will_take_me_days', {count: 3}); // It'll take me 3 days
i18n.t('it_will_take_me_days', {count: 'a lot of'}); // It'll take me a lot of days

Instance with a scope

Priority:

  1. Found result with passed in scope (when applicable)
  2. Found result with instance set scope (when applicable)
  3. Found result w/o scope
// Global scope setup
const i18n = new I18n({
    translations: {
        key: 'Top',
        child: {
            key: 'Child'
        },
        something: {
            key: 'Something'
        }
    }
});
const child = i18n.spawn('child');

i18n.t('key'); // Top
child.t('key'); // Child
child.t('key', { $scope: 'something' }); // Something

Scoped child instance

This is a good option for shorthand in enclosed parts of the application.

The translation store is shared so the parent can find the keys if it prefixes the namespace, and the child doesn't need to.

The child can also find "global" translations (ones that are outside it's namespace)

const usersI18n = i18n.spawn('users.get');

// Add translations under the scope
usersI18n.add({introduction: 'Hi, my name is %{username}'});

// Use translations
usersI18n.t('introduction', {username: 'Martin'}); // Hi, my name is Martin
i18n.t('users.get.introduction', {username: 'Martin'}); // Hi, my name is Martin

Instance

Exposes an empty instance of i18n

const i18n = require('@fiverr/i18n/instance');

i18n.add({...});

Made especially for use as a webpack external

externals: {
  '@fiverr/i18n/instance': 'i18n'
}

Name can alternate:

import phraser from '@fiverr/i18n/instance';
externals: {
  '@fiverr/i18n/instance': 'phraser'
}

Singleton (i18n)

Make sure you only have one instance of I18n in your global scope

const i18n = I18n.singleton;

// Optional:
i18n.$scope = 'my.scope';
i18n.onmiss((key, scope) => console.error(`Missing key "${key}" ${scope ? `In scope: "${scope}"`}`));
i18n.onempty((key, value, scope) => console.warn(`Empty value "${value}" for key "${key}" ${scope ? `In scope: "${scope}"`}`));
i18n.add({...});

Shortcut:

const i18n = require('@fiverr/i18n/singleton');

Or simply

require('@fiverr/i18n/singleton');

// i18n is defined globally

Helper functions

Check if a key is available

has

i18n.has('key');
i18n.has(['key', 'other_key']);
i18n.has('namespace.key');
i18n.has('key', { $scope: 'namespace' });

版本与发布记录

@fiverr/i18n 共发布 58 个版本,首次发布于 2017/08/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.9.2latest2024/11/052 年前
1.9.2-rc-fdc15412023/11/103 年前
1.9.12023/10/173 年前
1.9.02023/10/163 年前
2.0.0-rc-077e4942023/09/293 年前
2.0.0-rc-e892c7b2023/09/123 年前

其他发布通道:2019-06-25-fix-scope-lookup-order → 2.0.0-rc-ee193ec,2020-04-02-revert → 1.8.3-rc-e8dbcf4,add-types_pre → 1.8.4-rc-35c577a,templates-support_pre → 1.9.0-rc-c6101c9,lion_484_templates_support_ci_test_pre → 2.0.0-rc-e8b1c60,lion_484_templates_support_ci_test_pre-ci_update → 2.0.0-rc-a2d6566。

关于 @fiverr/i18n 的常见问题

@fiverr/i18n 是什么?

Translation helper

如何安装 @fiverr/i18n?

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

@fiverr/i18n 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/fiverr__i18n 是否存在。

@fiverr/i18n 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@fiverr/i18n 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=6.9.4。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@fiverr/i18n 可以商用吗?

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

@fiverr/i18n 的下载量有多少?

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

@fiverr/i18n 还在维护吗?

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