i18n
i18n 工具
用法
i18n 默认提供 FileSyncAdapter、ObjectAdapter 两个适配器,适用的场景分别为: locales 信息保存在文件中和 locales 信息保存在对象中。
import { I18n, FileSyncAdapter, ObjectAdapter } from '@picgo/i18n';
const fileSyncAdapter = new FileSyncAdapter({
localesBaseDir: path.resolve(__dirname, './locales'),
});
const i18n = new I18n({
adapter: fileSyncAdapter,
defaultLanguage: 'zh',
});
const objectAdapter = new ObjectAdapter({
zh: {
user: {
name: 'PicGo',
country: '中国',
},
report: {
singular: ' ${cnt}个报告',
plural: '${cnt}个报告',
},
},
en: {
user: {
name: 'PicGo',
country: 'China',
},
report: {
singular: 'only ${cnt} report',
plural: '${cnt} reports',
},
},
});
const i18n = new I18n({
adapter: objectAdapter,
defaultLanguage: 'zh',
});
自定义 Adapter
import { BaseAdapter } from 'i18n';
class CustomAdapter extends BaseAdapter {
getLocale(language) {}
}
API
I18n
-
i18n.setLanguage
-
i18n.getLauguage
-
i18n.translate
{
"report": {
"singular": "only ${cnt} report",
"plural": "${cnt} reports"
}
}
i18n.translate('report.singular', { cnt: 1 });
FileSyncAdapter
ObjectAdapter
-
构造函数 ObjectAdapter
- 参数 locales, 保存 locales 信息的对象
{
"zh": {
"user": {
"name": "PicGo",
"country": "China"
},
"report": {
"singular": " ${cnt}个报告",
"plural": "${cnt}个报告"
}
},
"en": {
"user": {
"name": "PicGo",
"country": "China"
},
"report": {
"singular": "only ${cnt} report",
"plural": "${cnt} reports"
}
}
}
-
objectAdapter.getLocale
- 参数 languag, 语言类型
- 返回 language 对应的 locale 数据
-
objectAdapter.setLocales 用于动态修改 objectAdapter 上的 locales 数据
- 参数 locales, locales 数据
- 无返回值
objectAdapter.setLocales({
zh: {
newData: 'this is new Data',
},
});
License
MIT
Copyright (c) 2020 PicGo Group