Files

22 lines
804 B
TypeScript
Raw Permalink Normal View History

import { tryUseNuxtApp } from '#app';
/**
* Synchronous translation helper usable outside of Vue components.
*
* It resuses the request-scoped `@nuxtjs/i18n` instance exposed on the Nuxt app
* as `$i18n`, so translations stay in sync with the active locale (including
* server-side rendering and language switches). Falls back to the raw key when
* no Nuxt context is available (e.g. in unit tests).
*
* @param key Translation key
* @param named Named/list arguments forwarded to vue-i18n
* @returns The translated string, or `key` when no i18n instance is found
*/
export const t = <T extends string = string>(key: T, named?: Record<string, unknown> | unknown[]): string => {
const i18n = tryUseNuxtApp()?.$i18n;
if (!i18n) {
return key;
}
return i18n.t(key, named as never);
};