const path = require('path'); const paths = require('./paths'); const localesHash = require('../i18n/localesHash'); const resourcesHash = require('../i18n/resourcesHash'); const COUNTRY = process.env.COUNTRY || 'sg'; const country = (COUNTRY).toUpperCase(); const defaultLng = localesHash[country][0]; const langs = [ 'en', 'id' ]; const prefixLangs = []; const entries = {}; for (let i = 0, len = langs.length; i < len; i++) { const prefixLang = `dict_${langs[i]}` prefixLangs.push(prefixLang) entries[prefixLang] = path.resolve(paths.appSrc, `../i18n/locales/${langs[i]}.json`) } const resources = { [defaultLng]: { common: resourcesHash[defaultLng] } } exports.resources = resources; exports.defaultLng = defaultLng;
逻辑也比较简单, 根据语言列表把对应的json 内容加进来。 作为示例,这里我设置的是 英文 和 印尼语。
下面看 i18n 文件里面的内容:
locales 里面放的是语言的json 文件, 内容大概是:
{ "msg_Created": "Pesanan telah terbuat" // ... }
localesHash.js:
module.exports = { SG: ['en'], ID: ['id'] }
resourcesHash.js:
module.exports = { 'en': require('./locales/en.json'), 'id': require('./locales/id.json') }
index.js
const path = require('path') const fs = require('fs') const fetch = require('isomorphic-fetch') const localesHash = require('./localesHash') const argv = process.argv.slice(2) const country = (argv[0] || '').toUpperCase() const i18nServerURI = locale => { const keywords = { 'en': 'en', 'id': 'id' } const keyword = keywords[locale] return keyword === 'en' ? 'xxx/json/download' : `/${keyword}/json/download` } const fetchKeys = async (locale) => { const uri = i18nServerURI(locale) console.log(`Downloading ${locale} keys...\n${uri}`) const respones = await fetch(uri) const keys = await respones.json() return keys } const access = async (filepath) => { return new Promise((resolve, reject) => { fs.access(filepath, (err) => { if (err) { if (err.code === 'EXIST') { resolve(true) } resolve(false) } resolve(true) }) }) } const run = async () => { const locales = localesHash[country] || Object .values(localesHash) .reduce( (previous, current) => previous.concat(current), [] ) if (locales === undefined) { console.error('This country is not in service.') return } for (const locale of locales) { const keys = await fetchKeys(locale) const data = JSON.stringify(keys, null, 2) const directoryPath = path.resolve(__dirname, 'locales') if (!fs.existsSync(directoryPath)) { fs.mkdirSync(directoryPath) } const filepath = path.resolve(__dirname, `locales/${locale}.json`) const isExist = await access(filepath) const operation = isExist ? 'update' : 'create' console.log(operation) fs.writeFileSync(filepath, `${data}\n`) console.log(`${operation}\t${filepath}`) } } run();
再看下src 中的配置:
i18nn.js
import i18next from 'i18next' import { firstLetterUpper } from './common/helpers/util'; const env = process.env; let LANGUAGE = process.env.LANGUAGE; LANGUAGE = typeof LANGUAGE === 'string' ? JSON.parse(LANGUAGE) : LANGUAGE const { defaultLng, resources } = LANGUAGE i18next .init({ lng: defaultLng, fallbackLng: defaultLng, defaultNS: 'common', keySeparator: false, debug: env.NODE_ENV === 'development', resources, interpolation: { escapeValue: false }, react: { wait: false, bindI18n: 'languageChanged loaded', bindStore: 'added removed', nsMode: 'default' } }) function isMatch(str, substr) { return str.indexOf(substr) > -1 || str.toLowerCase().indexOf(substr) > -1 } export const changeLanguage = (locale) => { i18next.changeLanguage(locale) } // Uppercase the first letter of every word. abcd => Abcd or abcd efg => Abcd Efg export const tUpper = (str, allWords = true) => { return firstLetterUpper(i18next.t(str), allWords) } // Uppercase all letters. abcd => ABCD export const tUpperCase = (str) => { return i18next.t(str).toUpperCase() } export const loadResource = lng => { let p; return new Promise((resolve, reject) => { if (isMatch(defaultLng, lng)) resolve() switch (lng) { case 'id': p = import('../i18n/locales/id.json') break default: p = import('../i18n/locales/en.json') } p.then(data => { i18next.addResourceBundle(lng, 'common', data) changeLanguage(lng) }) .then(resolve) .catch(reject) }) } export default i18next
// firstLetterUpper export const firstLetterUpper = (str, allWords = true) => { let tmp = str.replace(/^(.)/g, $1 => $1.toUpperCase()) if (allWords) { tmp = tmp.replace(/\s(.)/g, $1 => $1.toUpperCase()) } return tmp; }
这些准备工作做好后, 还需要把i18n 注入到app中:
index.js: