angelorigo's avatar

Laravel 12 with Inertia and Vuejs separate files for internationalization

Hi,

I am using the laravel 12 with inertia and Vuejs i do implement the internationalization feature, how can i avoid loading all json internationalization files at each request?

I am looking to maintain performance.

How can i separate each json file only for the page that is being requested at that time ?

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To optimize internationalization (i18n) in a Laravel 12 + Inertia + Vue.js setup and avoid loading all JSON translation files on every request, you can implement lazy-loading or code-splitting for your translation files. Here’s how you can achieve this:

1. Organize Your Translation Files

Structure your translation files per page or module, for example:

resources/js/lang/
  ├── home.en.json
  ├── home.fr.json
  ├── dashboard.en.json
  └── dashboard.fr.json

2. Use Dynamic Imports in Vue

Instead of importing all translations upfront, use dynamic imports to load only the necessary translation file for the current page.

Example using vue-i18n:

// i18n.js
import { createI18n } from 'vue-i18n';

const i18n = createI18n({
  legacy: false,
  locale: 'en', // default
  messages: {}, // start empty
});

export async function loadLocaleMessages(page, locale) {
  const messages = await import(
    /* @vite-ignore */
    `./lang/${page}.${locale}.json`
  );
  i18n.global.setLocaleMessage(locale, messages.default);
  i18n.global.locale.value = locale;
}

export default i18n;

3. Load Translations Per Page

In your Vue page component, load the translation file when the component is created or mounted:

<script setup>
import { onMounted } from 'vue';
import { loadLocaleMessages } from '../i18n';

onMounted(async () => {
  await loadLocaleMessages('home', 'en'); // dynamically set page and locale
});
</script>

4. Pass Page/Locale from Laravel

You can pass the current page and locale from Laravel to your Vue components via Inertia props:

// In your controller
return Inertia::render('Home', [
    'locale' => app()->getLocale(),
    'page' => 'home',
]);

5. Use Vite for Code Splitting

If you’re using Vite (default in Laravel 12), dynamic imports will automatically split your translation files into separate chunks, so only the needed file is loaded.


Summary:

  • Organize translations per page/module.
  • Use dynamic imports to load only the necessary translation file.
  • Pass the current page/locale from Laravel to Vue.
  • Let Vite handle the code splitting for optimal performance.

This approach ensures only the required translation file is loaded for each page, improving your app’s performance.

1 like
angelorigo's avatar

Where is located each file that needs to be edited ? eg. i18n.js ?

angelorigo's avatar

Into the step 3 Load Translations Per Page wich file must be edited ?

Please or to participate in this conversation.