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.