nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.71k stars 478 forks source link

How do I create tenant specific locale overrides for @nuxt-i18n locale files in Nuxt 3 project? #2861

Open garbit opened 6 months ago

garbit commented 6 months ago

I have a Nuxt 3 project that's using @nuxtjs/i18n v8.2.0) and I'm trying to create an override system that allows tenants to override the existing locale strings in the application by merging the existing locale file with a tenant specific override file.

I have a system that works currently that uses an i18n.config.ts file that manually imports each file I need. The imports use an import alias that I've defined in my nuxt.config.ts (@tenant).

How do I do this more efficiently so that I dynamically import all the locale files and associated override files automatically rather than manually importing and merging each locale file and creating the final messages object in the i18n.config.ts?

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@nuxtjs/i18n',
  ],
  i18n: {
    vueI18n: './i18n.config.ts',
  },
  alias: {
    // eslint-disable-next-line node/prefer-global/process
    '@tenant': `./assets/${process.env.NUXT_PUBLIC_TENANT_ID}`,
  },
  runtimeConfig: {
    public: {
      tenantId: '',
    },
  },
})
// i18n.config.ts
import deepmerge from 'deepmerge'

import tenantEn from '@tenant/locales/en.json'
import tenantAr from '@tenant/locales/ar.json'

import en from './locales/en.json'
import ar from './locales/ar.json'

export default defineI18nConfig(() => {
  const messages = {
    en: deepmerge(en, tenantEn),
    ar: deepmerge(ar, tenantAr),
  }

  return {
    legacy: false,
    locale: 'en',
    locales: ['en', 'ar'],
    messages,
  }
})
// locales/en.json
{
  "public": {
    "login": {
      "title": "Welcome!"
    }
  }
}

// assets/my-tenant/locales/en.json
{
  "public": {
    "login": {
      "title": "Welcome to the tenant string party!"
    }
  }
}

Folder structure:

locales/en.json <- standard language strings
assets/my-tenant/locales/en.json <- client specific overrides