前端另外一種多語言的實現思路

多語言i18n往常的作法是一個語言一個配置文件, 可是這樣須要添加一個新的字符串時, 須要逐個打開許多個語言文件, 經常會漏, 而且每次修改一個字符都要編輯好幾個文件. 咱們換一種思路, 把 i18n 的多語言直接寫在當前代碼中,而不是寫在配置文件中.node

思路

用一個方法,根據開發環境\當前瀏覽器語言去處理應該使用哪一個字符串, 而且暴露設置當前語言的函數,以兼容 nodejs 端或者開發人員擴展其餘語言. 該庫僅僅不到 70 行代碼, 實現一個精巧的i18fn.git

使用

安裝 i18fn 庫:github

$ npm i --save i18fn
複製代碼
const i18fn = require('i18fn');
const hello = i18fn.lang({ english: 'hello', chinese: '你好' });
console.log(hello);
複製代碼

使用參數

const i18fn = require('i18fn');
const personHello = i18fn.lang(
    { English: '__person__, hello', Chinese: '__person__, 你好' },
    {
      person: { English: 'Mr.Ming', Chinese: '小明' },
    },
  );
console.log(personHello);
});
複製代碼

自動語言缺失排查

若是瀏覽器語言是中文, 而你忘記添加中文的語言內容, 在開發模式中會作錯誤提示, 以下面這行代碼:npm

const say = i18fn.lang({ English: 'hello' });

// 在生產環境, i18fn 使用英文做爲代替
// 在開發環境, i18fn 會添加 - [Miss i18fn: languageType] 在英文後頭
if (process.env.NODE_ENV === 'production') {
  console.log(say); // hello
} else {
  console.log(say); // hello - [Miss i18fn: english]
}
複製代碼

設置當前語言

若是咱們要使用設置修改當前語言,能夠手動修改當前語言以覆蓋瀏覽器的語言識別:瀏覽器

const i18fn = require('i18fn');

i18fn.setNowLanguage('Chinese');
複製代碼

若是你仍是喜歡把 i18n 寫在配置文件裏

若是咱們但願文案能夠更好的複用, 咱們也能夠這樣把多個語言寫在一個文件中:bash

const { lang } = require('i18fn');
const languages = {
  done: lang({ English: 'done!', Chinese: '完成!' }),
  hello: lang({ English: 'hello', Chinese: '你好' }),
};

// use
console.log(languages.done);
console.log(languages.hello);
複製代碼

當前支持自動識別的語言

  • English
  • Chinese
  • ChineseTraditional
  • Dutch
  • Korea
  • French
  • German
  • Japanese
  • Italian
  • Portuguese
  • Spanish
  • Swedish
  • Russian
  • Arabic
  • Vietnamese
  • Polish
  • Finnish
  • Afrikaans
  • Khmer
  • Thai
  • Turkish
  • Ukrainian
  • Zulu

增長其餘語言判斷

若是你的應用須要添加匈牙利, 你能夠這樣:函數

const i18fn = require('i18fn');

i18fn.addLanguage('hu-HU', 'Magyar');

// ok like default use:
const hello = i18fn.lang({ English: 'hello', Magyar: 'helló' });
console.log(hello);
複製代碼

測試可靠性

安裝測試包:測試

$ yarn install && yarn test
複製代碼

你能夠嘗試測試, 測試內容編寫在 src/index.test.js, 如下是經過的測試:ui

$ jest
 PASS  src/index.test.js
  ✓ test chinese (4ms)
  ✓ test english
  ✓ test english params (1ms)
  ✓ test english params, use object
  ✓ test config
  ✓ test config function (1ms)
  ✓ test error chinese
  ✓ test error english
  ✓ test error chinese prod
  ✓ test error english prod (1ms)
  ✓ test add other language

Test Suites: 1 passed, 1 total
Tests:       10 passed, 10 total
Snapshots:   0 total
Time:        1.257s
Ran all test suites.
✨  Done in 1.80s.
複製代碼

這就是所有, 謝謝!spa

i18fn is MIT licensed.

Github 地址

github.com/ymzuiku/i18…

相關文章
相關標籤/搜索