在写一个APP的过程当中, 不免会遇到要作国际化的时候. 也就是须要根据不一样的地区, 展现不一样的文案. 对于简单的文本, 直接用一个xml或者json或者一个变量就能搞定, 可是有时候须要在一句话中加入变量, 就比较麻烦或者说比较恶心了. 好比这样的状况:node
cn: 有xx我的喜欢了你. en: xx People liked you.
i18n-json-compiler应运而生, 其做用是将json模板编译成TypeScript(或者JavaScript)函数或者字符串.git
好比对如下json:github
[ { "cn": "你好", "en": "Hello" }, { "cn": "{n}个好友", "en": "{n} friends" }, ]
能够直接编译出ts文件, 内容大体以下:typescript
export const cn = { Hello: "你好", n_friends: (n: any) => n + "个好友", } export const en = { Hello: "Hello", n_friends: (n: any) => n + " friends", }
在代码中直接调用相应的属性或函数便可.npm
yarn add i18n-json-compiler # 或者使用npm/cnpm npm i -S i18n-json-compiler
在命令行中, 执行./node_modules/.bin/i18n
, 参数以下:json
i18n [options] - Parse i18n json files to typescript files. Options: -i, --input-files The json files to parse [string] [required] -o, --output-dir The directory to emit output [string] [required] -h, --help Show help [boolean] -v, --version Show version number [boolean] --default-lang [string] [default: "cn"]
i18n
命令接受参数-i
指定输入文件列表(glob), 好比./strings/*.json
, 文件格式为json
, 内容为一个数组. 每一个数组元素为一组须要编译的字符串. key为语言, value为值. 值中被{}
包起来的地方会被转换为函数参数, 其格式为{name:type:default}
, 其中:数组
name
是必需的, 能够是字符串或数字type
为数据类型, 能够是int
, double
, string
, boolean
, any
, 默认为any
, 即接受任意参数default
为参数默认值好比:bash
[ { "cn": "{n:int:1}我的喜欢了你", "en": "{n}people liked you" } ]
得出的结果为:函数
const n_people_liked_you = (n: int = 1) => n + '我的喜欢了你'
i18n
接受参数-o
指定输出目录, 输入目录中, 包括一个index.ts
文件, 以及若干语言文件夹, 其中index.ts
为所用到的文件, 其导出一个变量strings
, 结构以下:ui
export interface I18n<T, L> { // 设置语言 set(lang: string, defaultLang?: L): void; // 获取语言下的字符串对象 get(lang: string, defaultLang?: L): T; // 当前语言 lang: L; // 当前语言的字符串结构 value: T; }
参考https://github.com/acrazing/i..., 其中input
为输入目录, output
为输出目录. 在代码中, 只须要:
import { strings } from './output/index.ts' console.log(strings.value.world.$0_people_liked_you(1))
更多内容, 请稳步 https://github.com/acrazing/i...