国际化
国际化文件
在插件里,前后端的多语言文件都存放在 src/locale 文件夹里。
|- /plugin-i18n
|- /src
|- /locale # 多语言文件夹
|- en-US.ts # 英文语言
|- zh-CN.ts # 中文语言
在对应的多语言文件(/src/locale/${lang}.ts)里添加翻译词条就可以了,如果是初次添加的多语言文件,需要重启应用才能生效,可以查看 app:getLang 接口来校验翻译词条是否已添加成功。
默认地址:http://localhost:13000/api/app:getLang?locale=zh-CN
i18n 相关 API
- server
- app.i18n
- app.t(text, options)
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- client
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- useT()
- utils
- react-i18next
- useTranslation(ns)
- withTranslation(ns)
Server
app.i18n server
app.i18n 为全局 i18n 实例,一般用于 CLI 中。例如结合 inquirer 用于实现命令行的交互。
import select from '@inquirer/select';
import input from '@inquirer/input';
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.command('test-i18n').action(async () => {
const answer1 = await select({
message: 'Select a language',
choices: [
{
name: '中文',
value: 'zh-CN',
},
{
name: 'English',
value: 'en-US',
},
],
});
await this.app.changeLanguage(answer1);
const answer2 = await input({
message: app.i18n.t('Enter your name'),
});
console.log(app.i18n.t(`Your name is {{name}}`, { name: answer2 }));
});
}
}
app.t(text, options) server
ctx.i18n server
ctx.i18n 是全局 app.i18n 的 cloneInstance,每个请求的 ctx 完全独立,根据客户端语言响应多语言信息。
客户端请求参数可以放在 query string 里
GET /?locale=en-US HTTP/1.1
Host: localhost:13000
也可以放在 request headers 里(推荐)
GET / HTTP/1.1
Host: localhost:13000
X-Locale: en-US
示例
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.use(async (ctx, next) => {
if (ctx.path === '/api/test-i18n') {
ctx.body = `${ctx.i18n.t('Hello')} ${ctx.i18n.t('World')}`;
}
await next();
});
}
}
查看 http://localhost:13000/api/test-i18n?locale=zh-CN
ctx.t(text, options) server
plugin.t() server
Client
ctx.i18n client
ctx.t(text, options) client
plugin.t()
useT()
工具函数
tExpr(text) server client
react-i18next
useTranslation(ns) client
withTranslation(ns) client