laravel-vue-i18n

repository·main·Indexed 20 days ago

https://github.com/xico2k/laravel-vue-i18n

A Vue 3 plugin that bridges Laravel's localization system with Vue, allowing developers to use Laravel translation files (JSON or PHP) directly within Vue components. It supports reactive translations via wTrans(), pluralization with transChoice(), and integration with Vite and Webpack/Laravel Mix. Version 2.8.0.

Tokens
6.1K
Snippets
26
Records
30
Agent score
72%

What's inside laravel-vue-i18n

  1. How multiple I18n instances work

    main

    The I18n class encapsulates translation logic and the active language. You can create multiple instances of I18n to support different active languages within the same application (e.g., a main UI in English and a specific component in Portuguese).

    While each instance maintains its own active language, loaded language files are shared across all instances to prevent redundant network requests or memory usage.

    import { I18n } from 'laravel-vue-i18n'
    
    const resolver = lang => import(`./fixtures/lang/${lang}.json`)
    
    const i18nEn = new I18n({
        lang: 'en',
        resolve: resolver
    })
    const i18nPt = new I18n({
        lang: 'pt',
        resolve: resolver
    })
    
    i18nEn.trans('Welcome!') // outputs "Welcome!"
    i18nPt.trans('Welcome!') // outputs "Bem-vindo!"
  2. Enable PHP translations in Vite

    main

    To make your Laravel PHP translation files available in Vue, use the laravel-vue-i18n/vite plugin in your vite.config.js.

    • For Laravel >= 9, call i18n() without arguments.
    • For Laravel < 9, pass the path to your lang folder (e.g., i18n('resources/lang')).

    You can also provide additionalLangPaths to load translations from other directories. If a key exists in multiple paths, the last path provided takes priority.

    // vite.config.js
    import i18n from 'laravel-vue-i18n/vite';
    
    export default defineConfig({
        plugins: [
            // ... other plugins
            i18n(), // Laravel >= 9
            // i18n('resources/lang'), // Laravel < 9
    
            // With additional paths
            i18n({
                additionalLangPaths: [
                    'public/locales'
                ]
            }),
        ],
    });
  3. Setup with Vite

    main

    To use the plugin with Vite, pass an options object to .use(i18nVue, ...) containing a resolve function. The resolve function is responsible for loading your language JSON files.

    Standard Setup

    Use import.meta.glob to asynchronously resolve language files.

    SSR (Server Side Rendering)

    For SSR, the resolve method must not return a Promise. Use the eager: true option in import.meta.glob and return the .default property of the loaded module.

    // Standard Vite Setup
    import { createApp } from 'vue'
    import { i18nVue } from 'laravel-vue-i18n'
    
    createApp()
        .use(i18nVue, {
            resolve: async lang => {
                const langs = import.meta.glob('../../lang/*.json');
                return await langs[`../../lang/${lang}.json`]();
            }
        })
        .mount('#app');
    
    // SSR Setup
    createApp()
        .use(i18nVue, {
            lang: 'pt',
            resolve: lang => {
                const langs = import.meta.glob('../../lang/*.json', { eager: true });
                return langs[`../../lang/${lang}.json`].default;
            },
        })
        .mount('#app');
  4. Configure shared vs non-shared Vue plugin usage

    main

    When using the i18nVue plugin with Vue, you can choose between a shared instance or independent instances for each app.

    Shared Usage (Default)

    All Vue app instances share a single I18n class and the same active language. This is the default behavior when you call .use(i18nVue).

    Non-shared Usage

    By setting shared: false in the plugin options, each Vue app instance will maintain its own independent I18n instance and active language.

    // Shared usage (Default)
    import { i18nVue } from 'laravel-vue-i18n'
    
    const appA = createApp()
        .use(i18nVue, { lang: 'pt' })
        .mount('#app-1');
    
    const appB = createApp()
        .use(i18nVue)
        .mount('#app-2');
    
    // Calling trans() anywhere uses the shared instance
    import { trans } from 'laravel-vue-i18n'
    trans('Welcome!') // outputs "Bem-vindo!"
    
    // Non-shared usage
    const appA = createApp()
        .use(i18nVue, {
            lang: 'es',
            shared: false,
        })
        .mount('#app-1');
    
    const appB = createApp()
        .use(i18nVue, {
            lang: 'pt',
            shared: false,
        })
        .mount('#app-2');
  5. Setup with Webpack / Laravel Mix

    main

    To use the plugin with Webpack or Laravel Mix, register the plugin and provide a resolve function in your Vue app setup.

    Standard Setup

    Use import() for asynchronous loading.

    SSR (Server Side Rendering)

    For SSR, the resolve function should use require instead of returning a Promise.

    // Standard Webpack Setup
    import { createApp } from 'vue'
    import { i18nVue } from 'laravel-vue-i18n'
    
    createApp()
        .use(i18nVue, {
            resolve: lang => import(`../../lang/${lang}.json`),
        })
        .mount('#app');
    
    // SSR Setup
    createApp()
        .use(i18nVue, {
            lang: 'pt',
            resolve: lang => require(`../../lang/${lang}.json`),
        })
        .mount('#app');
  6. Configure i18nVue plugin options

    main

    When calling .use(i18nVue, options), you can provide the following configuration:

    OptionTypeDescription
    langstring (optional)The initial language. If not provided, it attempts to detect from the <html lang="..."> tag.
    fallbackLangstring (optional)The language to use if the requested lang is invalid or not provided. Default: en.
    fallbackMissingTranslationsboolean (optional)If true, the plugin will fallback to fallbackLang if a specific translation key is missing in the current language.
    resolvefunction (required)The function used to fetch/load language files.
    sharedboolean (optional)Whether to share the same I18n instance between different Vue apps. Default: true.
    onLoadfunction (optional)A callback function executed every time a language is loaded.
  7. How the I18n class and shared instance work

    main

    The library uses a singleton pattern via I18n.getSharedInstance().

    • Shared Mode: When the plugin is installed with shared: true (default), all calls to the exported functions (trans, wTrans, etc.) interact with the same global instance.
    • Manual Instances: You can create independent instances using new I18n(options) if you need multiple isolated i18n contexts.
    • Resetting: Calling reset() clears all loaded languages and resets the shared instance.
  8. Extend Laravel Mix with i18n

    main

    If you are using Laravel Mix, you can extend it with the i18n method to enable build-time processing of translation files. This allows the package to synchronize your Laravel translation files with your Vue application.

    To use it, call .i18n() on your Mix configuration and provide the path to your language files using .i18n('path/to/lang').

    const mix = require('laravel-mix');
    
    mix.i18n('lang')
       .js('resources/js/app.js', 'public/js');
  9. Install and use the i18nVue plugin

    main

    To integrate laravel-vue-i18n into your Vue application, use the i18nVue plugin. By default, it uses a shared instance across your app. When installed, it provides $t and $tChoice global properties for use in templates.

    import { createApp } from 'vue'
    import { i18nVue } from 'laravel-vue-i18n'
    
    const app = createApp(App)
    
    // Install the plugin
    app.use(i18nVue, {
      shared: true // default
    })
    
    app.mount('#app')
    import { createApp } from 'vue'
    import { i18nVue } from 'laravel-vue-i18n'
    
    const app = createApp(App)
    app.use(i18nVue)
    app.mount('#app')
  10. Avoid calling translation functions before plugin installation

    main
    If you import and call translation functions (like trans()) before the i18nVue plugin has been installed via .use(), the library will automatically create a shared I18n instance with default options to prevent fatal errors. However, this instance will not have your custom configuration (like language or resolvers), which can lead to unexpected behavior. Always ensure the plugin is installed before invoking translation methods.
  11. Handle reactive pluralization with wTransChoice()

    main

    The wTransChoice() method is the reactive version of transChoice(). Use it when you need the pluralized string to update automatically when the count or language changes.

    import { wTransChoice } from 'laravel-vue-i18n';
    
    // Inside setup()
    return {
        oneAppleLabel: wTransChoice('There is one apple|There are many apples', 1),
        multipleApplesLabel: wTransChoice('{0} There are none|[1,19] There are some|[20,*] There are many', 19)
    }