Child app internationalization (for developers)
Installation
Install the npm package into your project with any package manager: bun i @lovrabet/i18n or pnpm i @lovrabet/i18n
@lovrabet/i18n quick reference
Java
// 0. 安装
bun i @lovrabet/i18n
// 1. 初始化, 并设置本地词包
const $i18n = new I18n({
locale: {
"en-US": {"welcome": "Welcome to yt-i18n"},
"zh-CN": {"welcome": "欢迎使用 yt-i18n 国际化库"},
"ja-JP": {"welcome": "yt-i18n へようこそ"},
},
});
// 2. 判断当前语种
$i18n.getLang();
// 3. 设置当前语种
$i18n.setLang("zh-CN");
// 4. 一些配置
$i18n.setConfig({
defaultLang: "zh-CN",
langList: ["zh-CN", "en-US", "ja-JP"],
});
// 5. 编码使用 .t .get 均可, 推荐 .t
$i18n.t("welcome"); // 最简单的使用
$i18n.t("welcome", "欢迎"); // welcome key不存在的时候, 用"欢迎"替代
$i18n.t({ id: "welcome", dm: "欢迎" }); // 完整写法, 同上
// 带参数
$i18n.t("hello", { name: "Jeffery" });
// 带参数完整写法, 同上
$i18n.t(
{ id: "hello", dm: "Hello, {name}!" },
{ name: "Jeffery" }
)JSON
{
"welcome": "Welcome to yt-i18n",
"hello": "Hello: {name}", // 接收参数
// 支持 ID 嵌套, 使用时 $i18n.t("index.welcome", "欢迎")
// 推荐采用这种方式, 按工程文件目录结构存放
"index": {
"welcome": "Welcome to yt-i18n"
}
}Supported languages
| Code | Native name | Chinese name |
|---|---|---|
| zh-CN | 简体中文 | Chinese (Simplified) |
| en-US | English | English |
| ja-JP | 日本語 | Japanese |
| id-ID | Bahasa Indonesia | Indonesian |
| tr-TR | Türkçe | Turkish |
| ... |
Using it in a child app (demo)
Reference project: https://github.com/lovrabet/sub-app-react-demo/tree/i18n (note: it lives on the
i18nbranch)Language switching is handled centrally by the parent app, so child apps only need to extract their copy into locale packs.
Key places to look:
src/i18n: the i18n configuration and instancesrc/locales: locale pack files for every languagesrc/layouts: the files already internationalized for the demo — use them as a model for the rest of the project
Once your project is set up, you can hand the whole i18n pass to any Agent with a prompt like this:
Plain
对项目中所有文件进行 i18n 国际化处理,需要支持中文和英文,提取的词包放在 src/locales 目录下。参考方法:
$i18n.t("welcome", "欢迎"); // welcome key不存在的时候, 用"欢迎"替代
// 带参数
$i18n.t("hello", { name: "Jeffery" });
// 词包接收参数
{ "hello": "你好: {name}" }