Created
December 17, 2018 15:55
-
-
Save web-crab/e408bb0c49b20a76c58cd90e27859f7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. Установить yaml-loader | |
* 2. Создать файл ~/locales/[name].yaml | |
* | |
* Содержимое файла | |
* About: | |
* ru: О нас | |
*/ | |
import Vue from 'vue' | |
import VueI18n from 'vue-i18n' | |
Vue.use(VueI18n) | |
const MAIN_LANG = 'en' | |
const messages = (() => { | |
const localeFilesRequire = require.context('~/locales/', false, /\.yaml$/) | |
const localeObjects = localeFilesRequire.keys().map(localeFilesRequire) | |
const localesObject = localeObjects.reduce((acc, obj) => ({ ...acc, ...obj }), {}) | |
const messages = {} | |
for (let message in localesObject) { | |
const translationsObject = localesObject[message] | |
const langs = Object.keys(translationsObject) | |
messages[MAIN_LANG] = messages[MAIN_LANG] || {} | |
messages[MAIN_LANG][message] = message | |
langs.forEach((lang) => { | |
messages[lang] = messages[lang] || {} | |
messages[lang][message] = translationsObject[lang] | |
}) | |
} | |
return messages | |
})() | |
const langs = Object.keys(messages) | |
const lang = (() => { | |
const currentLang = localStorage.getItem('locale') | |
const browserLang = navigator && navigator.language.substr(0, 2) | |
const isBrowserLangSupport = langs.indexOf(browserLang) !== -1 | |
return currentLang || (isBrowserLangSupport && browserLang) || MAIN_LANG | |
})() | |
const i18n = (() => { | |
const instance = new VueI18n({ | |
messages, | |
locale: lang, | |
fallbackLocale: MAIN_LANG | |
}) | |
instance.langs = langs | |
instance.setLocale = (lang) => { | |
instance.locale = lang | |
localStorage.setItem('locale', lang) | |
} | |
return instance | |
})() | |
export default i18n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment