-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.ts
59 lines (50 loc) · 1.7 KB
/
i18n.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import axios from 'axios';
import en from '@/locales/en.json';
Vue.use(VueI18n);
export const defaultLanguage = localStorage.locale || process.env.VUE_APP_I18N_LOCALE || 'en';
const defaultFallbackLanguage = 'en';
export const i18n = new VueI18n({
locale: defaultFallbackLanguage,
fallbackLocale: defaultFallbackLanguage,
messages: {
[defaultFallbackLanguage]: en.messages
},
dateTimeFormats: {
[defaultFallbackLanguage]: en.dateTimeFormats
}
});
function setI18nLanguage (lang: string) {
i18n.locale = lang;
axios.defaults.headers.common['Accept-Language'] = lang;
axios.defaults.headers.common['Content-Language'] = lang;
document.querySelector('html')!.setAttribute('lang', lang);
return lang;
}
export function loadLanguageAsync (lang: string) {
const langRegex = /^[A-Za-z]{2,3}([_\-.][A-Za-z]{2,4}){0,2}$/;
// If lang is not a valid language identifier
if (!lang.match(langRegex)) {
throw new Error('Invalid language identifier');
}
// If the same language
if (i18n.locale === lang) {
return Promise.resolve(setI18nLanguage(lang));
}
// If the language was already loaded
if (i18n.availableLocales.includes(lang)) {
return Promise.resolve(setI18nLanguage(lang));
}
// If the language hasn't been loaded yet
return import(/* webpackChunkName: "lang-[request]" */ `@/locales/${lang}.json`).then(
messages => {
i18n.setLocaleMessage(lang, messages.default.messages);
i18n.setDateTimeFormat(lang, messages.default.dateTimeFormats);
return setI18nLanguage(lang);
},
() => {
throw new Error('Language "' + lang + '" could not be loaded, use fallback instead');
}
);
}