nuxt.jsvitenuxt3.js

$t - global i18n function does not work in nuxt composables


so i have this in my nuxt.config

 i18n: {
    lazy: true,
    langDir: '../locales',
    locales: getLocales(),
    defaultLocale: 'en',
    strategy: 'no_prefix',
    experimental: {
      autoImportTranslationFunctions: true,
    },
  },

and "nuxt": "^3.15.0",

Throughout my app, I can use $t() for localization without issues.
When I try to use it inside a composable, I get an error saying $t is not defined.

At the same time, const { t } = useI18n() works inside the composable.

Why is $t not available in composables, and is there a way to make it work?


Solution

  • You need to useI18n() inside your composable, as the $i18n instance is not available inside composables.
    Actually, inside composables, you may not call composables (see code:)

    // useExample.ts
    // Not OK
    export function useExample() {
        const coolFeature = useCoolFeature();
    
        function myExampleFn() {
            coolFeature()
        }
        
        return {
            myExampleFn
        }
    }
    
    // OK
    export function useExample() {
        function myExampleFn() {
            const coolFeature = useCoolFeature();
            coolFeature()
        }
        
        return {
            myExampleFn
        }
    }
    
    // In your case
    export function useExample() {
        function myExampleFn() {
            const i18n = useI18n();
            return i18n.t('Peace')
        }
        
        return {
            myExampleFn
        }
    }
    
    // Other approach would be, to inject the functionality needed into the composable.
    // This approach may be the fastest, see dependency injection as a pattern