OSDN Git Service

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