@gluonjs/i18n


@gluonjs/i18n / packages/i18n/src / I18n

Interface: I18n

Properties

fallbackLocale?

readonly optional fallbackLocale?: string | readonly string[]


fallbackLocales

readonly fallbackLocales: readonly string[]


locale

readonly locale: Ref<string>


namespaceStatus

readonly namespaceStatus: Ref<Readonly<Record<string, I18nNamespaceStatus>>>


ready

readonly ready: Ref<number>

Methods

d()

d(value, options?): string

Parameters

value

number | Date

options?

DateTimeFormatOptions

Returns

string


hydrate()

hydrate(snapshot): void

Parameters

snapshot

I18nSnapshot

Returns

void


loadNamespace()

loadNamespace(namespace): Promise<void>

Parameters

namespace

string

Returns

Promise<void>


n()

n(value, options?): string

Parameters

value

number

options?

NumberFormatOptions

Returns

string


setLocale()

setLocale(locale): Promise<void>

Parameters

locale

string

Returns

Promise<void>


snapshot()

snapshot(): I18nSnapshot

Returns

I18nSnapshot


t()

t(key, options?): string

Parameters

key

string

options?

TranslateOptions

Returns

string

Example

Retain the typed locale, readiness, namespace-loading, and translation operations exposed by the application service:

ts
import { createApp, html } from '@gluonjs/core';
import {
  createI18n,
  i18nKey,
  useI18n,
  type I18n,
  type I18nFallbackContext,
  type I18nMessages,
  type I18nNamespaceLoader,
  type I18nNamespaceState,
  type I18nNamespaceStatus,
  type I18nOptions,
  type I18nSnapshot,
  type I18nValue,
  type LocaleCode,
  type TranslateOptions,
} from '@gluonjs/i18n';

const fallbackLocale: LocaleCode = 'en';
const english = { title: 'Orbit lamp', greeting: 'Hello {name}' } satisfies I18nMessages;
const loadProduct: I18nNamespaceLoader = async (locale) =>
  locale === 'de' ? { title: 'Orbit-Leuchte' } : english;
const missing = (context: I18nFallbackContext) => `[${context.locale}] ${context.key}`;
const options = {
  locale: 'de',
  fallbackLocale,
  messages: { en: english },
  namespaces: { product: loadProduct },
  missing,
} satisfies I18nOptions;
const plugin = createI18n(options);
const i18n: I18n = plugin;
const translation = { namespace: 'product', values: { name: 'Mara' } } satisfies TranslateOptions;
const namespaceState: I18nNamespaceState = 'loading';
const namespaceStatus: I18nNamespaceStatus = { state: namespaceState };
const value: I18nValue = new Date();
const snapshot: I18nSnapshot = i18n.snapshot();

const ProductTitle = () => html`<h1>${useI18n().t('title', translation)}</h1>`;
createApp(ProductTitle).use(plugin).mount(document.querySelector('#app')!);
console.log(i18n.t('greeting', { values: { name: 'Mara' } }), i18nKey, namespaceStatus, value, snapshot);