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

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%的案件中使用了其他方法.