N
Nuxt6mo ago
Lijah

NuxtI18n - Access global i18n outside of components or even composables

I am trying to implement NuxtI18n after using VueI18n. In some composables, I can use useI18n() or useNuxtApp().$i18n. How can I achieve the same behavior as the code below in nuxtI18n?
// some utiltiy file that may be ran in a worker or outside

import i18n from "@/i18n";

...
export const someFunction = () => {
const formattedString = i18n.global.te(myStringToTranslate) ? i18n.global.t(myStringToTranslate) : myStringToTranslate;
}
...
// some utiltiy file that may be ran in a worker or outside

import i18n from "@/i18n";

...
export const someFunction = () => {
const formattedString = i18n.global.te(myStringToTranslate) ? i18n.global.t(myStringToTranslate) : myStringToTranslate;
}
...
I've tried things like this, but sometimes calling these composables throws errors
export const someFunction = () => {
const { t, te, } = useI18n();
//or
const { t, te, } = useNuxtApp().$i18n;
const formattedString = te(myStringToTranslate) ? t(myStringToTranslate) : myStringToTranslate;
}
export const someFunction = () => {
const { t, te, } = useI18n();
//or
const { t, te, } = useNuxtApp().$i18n;
const formattedString = te(myStringToTranslate) ? t(myStringToTranslate) : myStringToTranslate;
}
If I ran either in a composable, they usually work, but not always. Like when I run the composable in a worker
export function composable() {
const { t, } = useI18n() // blows up
};
export function composable() {
const { t, } = useI18n() // blows up
};
3 Replies
Lijah
LijahOP6mo ago
It really seems like my best bet is to skip nuxti18n entirely and create a manual plugin with vuei18n
dwol
dwol6mo ago
As long as youre using the composable inside of setup this should work const { t } = useI18n() For outside the context try const t = useNuxtApp().$i18n.t (do not destructure)
Lijah
LijahOP6mo ago
This still causes the same error when calling useNuxtApp without destructuring. Is it because it is being run on a worker thread? Perhaps I could pass context to the worker
Want results from more Discord servers?
Add your server