vue-i18n v8

repository·v8.x·Indexed 27 days ago

https://github.com/kazupon/vue-i18n

Internationalization plugin for Vue.js 2. Provides tools for managing translations, pluralization, and locale-sensitive formatting for dates and numbers. Includes the VueI18n class, $t, $tc, $te, $d, and $n methods, as well as the v-t directive and <i18n> and <i18n-n> functional components. Note: Version 8.x has reached End of Life (EOL); users of Vue 3 are recommended to use Vue I18n v9 or later.

Tokens
30.1K
Snippets
95
Records
157
Agent score
92%

What's inside vue-i18n

  1. Third-party i18n development tools

    v8.x

    Several third-party tools support Vue I18n development:

    • BabelEdit: A translation editor for web apps that can translate json files and i18n custom blocks in Single File Components.
    • i18n Ally: A VSCode extension designed to improve the developer experience (DX) for i18n development.
    • vue-i18n-extract: A static analysis tool for finding unused or missing translation keys.
  2. Official Vue I18n Tooling

    v8.x

    Vue I18n provides several official tools to support different build environments and frameworks:

    • Vue CLI Plugin: vue-cli-plugin-i18n sets up the i18n environment and supports the development environment for Vue CLI projects.
    • Nuxt Module: nuxt-i18n is the official module for Nuxt.js integration.
    • Webpack Loader: vue-i18n-loader allows you to use the i18n custom block within Single File Components (SFCs).
    • ESLint Plugin: eslint-plugin-vue-i18n integrates localization linting features into your Vue.js application.
    • Extensions: vue-i18n-extensions provides extensions to enable SSR (Server-Side Rendering) and improve i18n performance.
  3. Use <i18n> custom blocks in Single File Components

    v8.x

    You can manage locale messages directly within a Single File Component (SFC) using the <i18n> custom block. This allows you to define JSON-formatted locale messages specific to that component. These messages are merged with other locale messages available to the component.

    <i18n>
    {
      "en": {
        "hello": "hello world!"
      },
      "ja": {
        "hello": "こんにちは、世界!"
      }
    }
    </i18n>
    
    <template>
      <div id="app">
        <p>message: {{ $t('hello') }}</p>
      </div>
    </template>
  4. Configure implicit fallback using locales

    v8.x

    When a locale includes a territory and an optional dialect, vue-i18n automatically activates an implicit fallback chain. For example, the locale de-DE-bavarian will automatically attempt to resolve translations in this order:

    1. de-DE-bavarian
    2. de-DE
    3. de

    To disable this automatic behavior and prevent the chain, append an exclamation mark ! to the locale string (e.g., de-DE!).

  5. Verify Vue I18n version compatibility

    v8.x

    Vue I18n v8 is specifically designed for Vue 2 applications.

    If you are using Vue 3, you should use Vue I18n v9 or later instead of this version.

    Note on Maintenance: Vue I18n v8 is no longer actively maintained. Security hotfixes were only provided for version v8.28 until the end of 2024.

  6. Set up vue-i18n with a JavaScript module system

    v8.x

    If you are using a module system (such as vue-cli), import Vue and VueI18n, register the plugin using Vue.use(VueI18n), and create a new VueI18n instance. Pass this instance to your Vue application via the i18n option.

    // import Vue from 'vue'
    // import VueI18n from 'vue-i18n'
    //
    // Vue.use(VueI18n)
    
    const messages = {
      en: {
        message: {
          hello: 'hello world'
        }
      },
      ja: {
        message: {
          hello: 'こんにちは、世界'
        }
      }
    }
    
    const i18n = new VueI18n({
      locale: 'ja', // set locale
      messages, // set locale messages
    })
    
    new Vue({ i18n }).$mount('#app')
  7. Define Locale Messages structure

    v8.x

    Locale messages in vue-i18n can be structured as a nested object, an array, or a function. You can access nested values, array elements, or objects within arrays using dot notation and bracket notation.

    Supported Structures

    • Basic: A simple key-value pair where the value is a string.
    • Nested: Objects containing further keys.
    • Arrays: Lists of strings, objects, or even nested arrays.
    • Message Functions: Functions that receive a context object (ctx) and return a string for complex logic.

    Accessing Messages

    Use $t or t with the following path patterns:

    • Nested: nested.key
    • Array: array[0]
    • Object in Array: array[1].key
    • Nested Array: array[2][0]
    {
      "en": {
        "key1": "this is message1",
        "nested": {
          "message1": "this is nested message1"
        },
        "errors": [
          "this is 0 error code message",
          {
            "internal1": "this is internal 1 error message"
          },
          [
            "this is nested array error 1"
          ]
        ]
      }
    }
  8. Use component-based localization

    v8.x

    While locale information is typically set globally on the VueI18n instance, you can manage locale information for individual components using the i18n option. This allows components to have their own specific messages that take precedence over global messages. If a key is missing in the component's local messages, it will fall back to the global locale messages.

    To suppress console warnings when a component falls back to the root locale, set silentFallbackWarn: true in the VueI18n constructor.

    To use a specific locale for a component instead of the global one, use the locale option within the component's i18n object and set sync: false.

  9. Lazy load translation files with Webpack

    v8.x

    To avoid loading all translation files at once, you can use Webpack's dynamic import() function to load language files asynchronously. This involves maintaining a list of loadedLanguages to prevent redundant network requests and using i18n.setLocaleMessage to register the newly loaded messages into your VueI18n instance.

    Implementation Steps

    1. Initialize VueI18n with a default locale and messages.
    2. Maintain a loadedLanguages array to track which files have already been fetched.
    3. Create a loadLanguageAsync function that uses dynamic imports with a Webpack magic comment (e.g., /* webpackChunkName: "lang-[request]" */) to fetch the specific language file.
    4. Once the file is loaded, use i18n.setLocaleMessage(lang, messages.default) to add the messages to the instance.
    // i18n-setup.js
    import Vue from 'vue'
    import VueI18n from 'vue-i18n'
    import messages from '@/lang/en'
    import axios from 'axios'
    
    Vue.use(VueI18n)
    
    export const i18n = new VueI18n({
      locale: 'en',
      fallbackLocale: 'en',
      messages
    })
    
    const loadedLanguages = ['en']
    
    function setI18nLanguage (lang) {
      i18n.locale = lang
      axios.defaults.headers.common['Accept-Language'] = lang
      document.querySelector('html').setAttribute('lang', lang)
      return lang
    }
    
    export function loadLanguageAsync(lang) {
      if (i18n.locale === lang) {
        return Promise.resolve(setI18nLanguage(lang))
      }
    
      if (loadedLanguages.includes(lang)) {
        return Promise.resolve(setI18nLanguage(lang))
      }
    
      return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}.js`).then(
        messages => {
          i18n.setLocaleMessage(lang, messages.default)
          loadedLanguages.push(lang)
          return setI18nLanguage(lang)
        }
      )
    }
  10. Hot reload static locales using Webpack HMR

    v8.x

    If you are using a fixed set of localization files, you can use Webpack's Hot Module Replacement (HMR) to update the VueI18n instance without a full page reload. Use module.hot.accept to watch specific files and call i18n.setLocaleMessage with the newly required content.

    import Vue from "vue"
    import VueI18n from "vue-i18n"
    import en from './en'
    import ja from './ja'
    
    const messages = {
      en,
      ja
    }
    
    // VueI18n instance
    const i18n = new VueI18n({
      locale: 'en',
      messages
    })
    
    // Run app
    const app = new Vue({
      i18n,
      // ...
    }).$mount('#app')
    
    // Hot updates
    if (module.hot) {
      module.hot.accept(['./en', './ja'], function () {
        i18n.setLocaleMessage('en', require('./en').default)
        i18n.setLocaleMessage('ja', require('./ja').default)
        // Or the following hot updates via $i18n property
        // app.$i18n.setLocaleMessage('en', require('./en').default)
        // app.$i18n.setLocaleMessage('ja', require('./ja').default)
      })
    }
  11. Configure a single fallback locale

    v8.x

    You can define a single fallbackLocale in the VueI18n constructor. If a requested key is missing in the current locale, the system will look for that key in the specified fallbackLocale.

    const messages = {
      en: {
        message: 'hello world'
      },
      ja: {}
    }
    
    const i18n = new VueI18n({
      locale: 'ja',
      fallbackLocale: 'en',
      messages
    })