index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Vue from 'vue'
  2. import VueI18n from 'vue-i18n'
  3. import * as en from 'locales/en.json'
  4. import axios from 'axios'
  5. // import * as fr from 'locales/fr.json'
  6. Vue.use(VueI18n)
  7. const messages = {
  8. en: {
  9. ...en.default
  10. }
  11. }
  12. export const i18n = new VueI18n({
  13. locale: 'en',
  14. fallbackLocale: 'en',
  15. messages
  16. })
  17. const loadedLanguages = ['en'] // our default language that is preloaded
  18. function setI18nLanguage (lang) {
  19. i18n.locale = lang
  20. // axios.defaults.headers.common['Accept-Language'] = lang
  21. // document.querySelector('html').setAttribute('lang', lang)
  22. return lang
  23. }
  24. export function loadLanguageAsync (lang) {
  25. // If the same language
  26. if (i18n.locale === lang) {
  27. return Promise.resolve(setI18nLanguage(lang))
  28. }
  29. // If the language was already loaded
  30. if (loadedLanguages.includes(lang)) {
  31. return Promise.resolve(setI18nLanguage(lang))
  32. }
  33. // If the language hasn't been loaded yet
  34. // return import(/* webpackChunkName: "lang-[request]" */ `sites/default/files/lang/${lang}.json`).then(
  35. return axios.get(`/sites/default/files/lang/${lang}.json`)
  36. .then(({ data }) => {
  37. console.log(`webpack import ${lang} messages`, data)
  38. i18n.setLocaleMessage(lang, data)
  39. loadedLanguages.push(lang)
  40. return setI18nLanguage(lang)
  41. })
  42. }