Implement lazy loading for translations
mainTo avoid downloading all translations at once, you can use component name prefixes to split translation files into chunks.
- Prefix components: Use names like
main/postorsettings/userwhen callingi18n(). - Organize JSON: Store translations in files matching those prefixes (e.g.,
public/translations/ru/main.json). - Custom
getlogic: IncreateI18n, use thecomponentsargument in thegetfunction to identify which chunks need to be fetched.
When a component renders, i18n tracks which component names are used and triggers the get function for any missing prefixes.
export const i18n = createI18n(locale, {
async get(code, components) {
// Extract unique prefixes (e.g., 'main' from 'main/post')
let prefixes = components.map(name => name.split('/')[0])
let unique = Array.from(new Set(prefixes))
// Fetch only the required chunks
return Promise.all(
unique.map(chunk => fetchJSON(`/translations/${code}/${chunk}.json`))
)
}
})