[Vuejs]-Exclude translation when build VueJs project

0👍

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()
  })
})()

Leave a comment