I have a project that use vue-i18n for translations. This project is published on 2 servers, server 1 is only English, server 2 is only Swedish. Now i want to exclude languages that is not required. On server 1 i want to exclude swedish and only load english, server 2 exclude english and only load swedish. Is that possible? I have translations in components and in locales/*.json files.
In my i18n settings file:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
function loadLocaleMessages () {
const locales = require.context('@/locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
const messages = {}
locales.keys().forEach(key => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i)
if (matched && matched.length > 1) {
const locale = matched[1]
messages[locale] = locales(key)
}
})
return messages
}
export default new VueI18n({
locale: process.env.VUE_APP_LANG || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages(),
silentFallbackWarn: true
})
In my vue.config.js file:
pluginOptions: {
i18n: {
locale: process.env.VUE_APP_LANG,
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE,
localeDir: "locales",
enableInSFC: true,
},
},
One solution is to deploy a configuration file that specifies which locales are enabled. The app could then fetch that file, and read the config to determine which locale messages to load.
For example, deploy config.json in your static directory (e.g., public/ in Vue CLI scaffolded project).
Server 1: English only
// public/config.json
{
"locales": ["en"]
}
Server 2: Swedish only
// public/config.json
{
"locales": ["sv"]
}
App:
// i18n.js
async function loadLocaleMessages () {
const locales = require.context('@/locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
const messages = {}
const res = await fetch(process.env.VUE_APP_BASE_URL + '/config.json')
const config = await res.json()
locales.keys()
.filter(locale => config.locales.includes(locale)) ๐
.forEach(key => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i)
if (matched && matched.length > 1) {
const locale = matched[1]
messages[locale] = locales(key)
}
})
return messages
}
The plugin would then have to be async:
// i18n.js
export default async () => {
return new VueI18n({
locale: process.env.VUE_APP_LANG || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: await loadLocaleMessages(),
silentFallbackWarn: true
})
}
// main.js
import i18n from './i18n'
(async() => {
new Vue({
i18n: await i18n()
})
})()