How can I use i18n instance outside the setup function?

319 Views Asked by At

I am trying to use i18n in a typescript file as t(""), however, the strings are not getting translated instead complete string inside of the t() is printing. I have separate i18n.ts file as shown below.

export const install = (app: any) => {
  const i18n = createI18n({
    legacy: false,
    locale: "de",
    fallbackLocale: "de",
    messages,
    missingWarn: false,
    fallbackWarn: false,
    globalInjection: true,
    datetimeFormats: {
      de: {
        date: {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
        },
        dateTime: {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        },
      },
    },
  })
  app.use(i18n)

  const vuetify = createVuetify({
    components,
    directives,
    theme,
  })

  app.use(vuetify)
}

How can I use i18n in .ts file??

const { t } = { t: (key: string) => key };

const col = {
  label: t("location.remark"),
}
2

There are 2 best solutions below

1
On

I think the simplest way is to create the instance of i18n out the scope, and export it

export const i18n = createI18n({
    legacy: false,
    locale: "de",
    fallbackLocale: "de",
    messages,
    missingWarn: false,
    fallbackWarn: false,
    globalInjection: true,
    datetimeFormats: {
      de: {
        date: {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
        },
        dateTime: {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        },
      },
    },
  })
  
  export const install = (app: any) => {
  
  app.use(i18n)

  const vuetify = createVuetify({
    components,
    directives,
    theme,
  })

  app.use(vuetify)
}

second step: create the instance in a i18n.ts file and import it

import {i18n} from './i18n'
  
  export const install = (app: any) => {
  
  app.use(i18n)

  const vuetify = createVuetify({
    components,
    directives,
    theme,
  })

  app.use(vuetify)
}

third step is to import the i18n instance wherever you want in the vue/ts/js files :D

0
On

Another solution is to convert your .ts file as a composable then inject t like this: const { t } = useI18n();

More info here: https://vue-i18n.intlify.dev/guide/advanced/composition.html#composition-api