Skip to content

Instantly share code, notes, and snippets.

@ashour
Last active March 10, 2021 18:25
Show Gist options
  • Save ashour/3d2151446cf2b46552bf1d34916ac3f5 to your computer and use it in GitHub Desktop.
Save ashour/3d2151446cf2b46552bf1d34916ac3f5 to your computer and use it in GitHub Desktop.
import Vue from "vue"
import VueI18n from "vue-i18n"
import getBrowserLocale from "@/util/i18n/get-browser-locale"
import { supportedLocalesInclude } from "./util/i18n/supported-locales"
import {
getChoiceIndex,
setDefaultChoiceIndexGet
} from "./util/i18n/choice-index-for-plural"
import dateTimeFormats from "@/locales/date-time-formats"
import numberFormats from "@/locales/number-formats"
import EventBus from "@/EventBus"
Vue.use(VueI18n)
// Mixin the formatDate function to make it globally available in all components
Vue.mixin({
methods: {
formatDate
}
})
function getStartingLocale() {
const browserLocale = getBrowserLocale({ countryCodeOnly: true })
if (supportedLocalesInclude(browserLocale)) {
return browserLocale
} else {
return process.env.VUE_APP_I18N_LOCALE || "en"
}
}
setDefaultChoiceIndexGet(VueI18n.prototype.getChoiceIndex)
VueI18n.prototype.getChoiceIndex = getChoiceIndex
const startingLocale = getStartingLocale()
const i18n = new VueI18n({
locale: startingLocale,
messages: {},
dateTimeFormats,
numberFormats
})
const loadedLanguages = []
export function loadLocaleMessagesAsync(locale) {
EventBus.$emit("i18n-load-start")
if (loadedLanguages.length > 0 && i18n.locale === locale) {
EventBus.$emit("i18n-load-complete")
return Promise.resolve(locale)
}
// If the language was already loaded
if (loadedLanguages.includes(locale)) {
i18n.locale = locale
EventBus.$emit("i18n-load-complete")
return Promise.resolve(locale)
}
// If the language hasn't been loaded yet
return import(
/* webpackChunkName: "locale-[request]" */ `@/locales/${locale}.json`
).then(messages => {
i18n.setLocaleMessage(locale, messages.default)
loadedLanguages.push(locale)
i18n.locale = locale
EventBus.$emit("i18n-load-complete")
return Promise.resolve(locale)
})
}
// ---- START NEW FUNCTIONS -----
function getDefaultFullyQualifiedLocaleFor(countryCode) {
if (countryCode === "ar") {
return "ar-EG"
} else {
return "en-US"
}
}
function formatDate(date, dateStyle, countryCode = null) {
const locale = getDefaultFullyQualifiedLocaleFor(countryCode || i18n.locale)
return new Intl.DateTimeFormat(locale, { dateStyle }).format(date)
}
// ---- END NEW FUNCTIONS -----
export default i18n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment