R
R
ravshan selimov2021-01-27 13:23:47
Internationalization and localization
ravshan selimov, 2021-01-27 13:23:47

How to tell i18n to look for files in all folders?

Hello.
I am using i18n in a Vue project.
Structure:

/public
/src
  /locales
  /views
  /other folders
  App.vue
  main.js
  i18n.js
package.json


I want it to take files not only from the locales folder, but from any folder, for example, take /views/HomePage/HomePage.locales.json

i18n.js
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); // делаю так ничего не работает - './' или '.' вместо './locales
  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_I18N_LOCALE || 'ru',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'ru',
  messages: loadLocaleMessages()
})


vue.config.js
module.exports = {
  "transpileDependencies": [
    "vuetify"
  ],

  pluginOptions: {
    i18n: {
      locale: 'ru',
      fallbackLocale: 'uz',
      localeDir: 'locales', // пробовал заменить на src не работает
      enableInSFC: true
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2021-01-27
@ravshan01

You have the enableInSFC: true option enabled .
In vue files you can write like this:

<!-- /views/HomePage/HomePage.vue -->
<i18n src="./HomePage.locales.json"></i18n>

Thus, in the context of this vue file, the translations from HomePage.locales.json will override the global ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question