use translation files dynamically based on the route (load different files per page) nuxt3 and i18n?

77 Views Asked by At

what i am trying to combine shared translation with page specific translation using a global middleware

the issue i am facing is that in the server side it works fine , but in the browser after the hydration done the change done in the server side will be removed and the shared translation only will work , and using langTexts = await import(); doesn't work on the client side

i am not sure if the middleware approach is the correct way to it or there could be a better way , also i went thorough the docs of nuxt/i18n https://i18n.nuxtjs.org/guide/routing-strategies and couldn't find away to do it ,, would a plugin be a good idea ? its important for me for the content to not show the keys to the user then show the actual translation

the example route : http://localhost:3000/ar/a/test

translation files structure :
enter image description here

//00.locale.global.js
export default defineNuxtRouteMiddleware(async (to, from) => {
  try {
    const { locale, setLocaleMessage, getLocaleMessage, mergeLocaleMessage } = useNuxtApp().$i18n
    const route = to.name;
    const lang = getLang(route);
    const pageName = getPageName(route)
    const path = getPath(pageName, lang);
    console.log(lang, pageName, path); // ar a-test a/test/ar.json
    var langTexts
    if (process.server) {
      if (pageName != "index") {
        langTexts = await import(`~/translation/${path}`);
        mergeLocaleMessage(lang, langTexts.default);
      }
    }
    if (process.client) {
      console.log('process.client', langTexts); // this is undefined 
      console.log('process.client', getLocaleMessage(lang)); // this only show the translation form /translation/shared/[lang].json
    }
  } catch (e) {
    console.error(`translation file err` , e);
  }
});

function getLang(route) {
  const lastUnderscorePos = route.lastIndexOf('_');
  const result = route.substring(lastUnderscorePos + 1, lastUnderscorePos + 3);
  return result;
}

function getPageName(route) {
  const lastUnderscorePos = route.indexOf('_');
  const result = route.substring(0, lastUnderscorePos);
  return result;
}

function getPath(inputString, lang) {
  return inputString.split('-').join('/') + '/' + lang + '.json';
}
//nuxt.config.ts
export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: ["@nuxtjs/i18n"],
  i18n: {
    lazy: true,
    langDir: "translation/shared",
    strategy: "prefix",
    locales: [
      { code: 'en', iso: 'en-US', file: 'en.json', name: 'English' },
      { code: 'fr', iso: 'fr-FR', file: 'fr.json', name: 'Français' },
      { code: 'ar', iso: 'ar', file: 'ar.json', name: 'العربية' }
    ],
    defaultLocale: "en",
    customRoutes: 'config',
  },
})
0

There are 0 best solutions below