i18n.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. The i18n module, loads the language files and initializes i18next
  3. @module i18n
  4. */
  5. const fs = require('fs');
  6. const i18n = require('i18next');
  7. const extend = require('lodash/extend');
  8. let i18nConf = fs.readFileSync(`${__dirname}/../interface/project-tap.i18n`);
  9. i18nConf = JSON.parse(i18nConf);
  10. const resources = {
  11. dev: { translation: require('../interface/i18n/mist.en.i18n.json') }
  12. };
  13. // add supported languages
  14. i18nConf.supported_languages.forEach(lang => {
  15. const mistTranslations = require(`../interface/i18n/mist.${lang}.i18n.json`);
  16. const uiTranslations = require(`../interface/i18n/app.${lang}.i18n.json`);
  17. resources[lang] = { translation: extend(mistTranslations, uiTranslations) };
  18. });
  19. /**
  20. * Given a language code, get best matched code from supported languages.
  21. *
  22. * > getBestMatchedLangCode('en-US')
  23. * 'en'
  24. * > getBestMatchedLangCode('zh-TW')
  25. * 'zh-TW'
  26. * > getBestMatchedLangCode('no-such-code')
  27. * 'en'
  28. */
  29. i18n.getBestMatchedLangCode = langCode => {
  30. const codeList = Object.keys(resources);
  31. let bestMatchedCode = langCode;
  32. if (codeList.indexOf(langCode) === -1) {
  33. if (codeList.indexOf(langCode.substr(0, 2)) > -1) {
  34. bestMatchedCode = langCode.substr(0, 2);
  35. } else {
  36. bestMatchedCode = 'en';
  37. }
  38. }
  39. return bestMatchedCode;
  40. };
  41. // init i18n
  42. i18n.init({
  43. lng: global.language || 'en',
  44. resources,
  45. interpolation: { prefix: '__', suffix: '__' }
  46. });
  47. module.exports = i18n;