i18n-json-compiler 一個爲TypeScript編寫的國際化方案

在寫一個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"]

JSON文檔的格式

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))

TODO

  • 編譯成js
  • 不一樣語言參數位置不一樣
  • 指定名稱key

更多內容, 請穩步 https://github.com/acrazing/i...

相關文章
相關標籤/搜索