Modules

Starter modules

Localization

prefab-i18n@0.1.1

Localized strings and voice-over from your own bundle: Intl plurals/number/date, per-locale lazy loading, audio fallback chain.

Version
0.1.1
License
MIT
Size
3 KB
Runs on
Desktop and mobile browsers.

Add it

Declare it in prototir.json at the root of your ZIP. Prototir checks the version at upload and adds it to the page's import map.

prototir.json
{
  "modules": [
    "prefab-i18n@0.1.1"
  ]
}

Then import it by name, from 'prefab-i18n', as you would from npm.

Smallest example

Example
import { createI18n } from 'prefab-i18n';

const i18n = await createI18n({
  locales: ['en', 'it'],
  fallback: 'en',
  loadStrings: (locale) => fetch(`locales/${locale}.json`).then((r) => r.json())
});

title.textContent = i18n.t('play');
coins.textContent = i18n.t('coins', { count: 3 });

API

createI18n(options)

locales = ['en'], fallback = locales[0]
The languages you publish, and the one used when a key is missing.
locale, preferred
Force a starting locale, or pass the player's preference list; otherwise the browser's languages are used.
strings, loadStrings(locale)
Inline tables, or a loader called for one locale at a time. Only the active locale (and the fallback) is ever fetched.
audio: { base, map, locales? }
Voice-over from your bundle at base/locale/file. locales narrows it to the languages you recorded.
onChange(locale)
Called after setLocale switches language.

The returned i18n

i18n.t(key, vars)
Translates a key, filling {placeholders}. With vars.count, picks the plural form ({ one, other, ... }) via Intl.PluralRules. A missing key returns the key itself.
i18n.number(value, options), i18n.date(value, options)
Locale-aware formatting through Intl.
await i18n.setLocale(locale)
Switches language, loading its strings on demand.
i18n.locale, i18n.locales, i18n.fallback
The current state.
await i18n.playAudio(key, { volume, loop }), i18n.stopAudio()
Plays a localized clip, falling back to the fallback locale. Returns null when the browser blocks autoplay.
await i18n.preloadAudio(keys?)
Preloads the active locale's clips.
i18n.destroy()
Stops audio and clears caches.

Also exported

negotiateLocale(preferred, available, fallback)
Picks the best available locale for a preference list.

Good to know

  • Built for the sandbox: a prototype cannot reach translation services, so everything resolves from your own bundle.

Versions

Every version stays available, so a prototype keeps working exactly as published. Declare the one you tested with.

  • prefab-i18n@0.1.1
  • prefab-i18n@0.1.0

As JSON: /modules/prefab-i18n.json. Source: prototir.