Localization Manager
Shows the game’s text in several languages, with fill-in values, correct plurals for each language, number formats, right-to-left languages and a list of missing translations.
Files: localization-manager.js (the component, no dependencies) and localization-manager.test.mjs (5 tests).
Copy localization-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createI18n } from "./localization-manager.js";
const i18n = createI18n({
fallback: "en",
locales: {
en: { menu: { start: "Start" }, coins: { one: "{count} coin", other: "{count} coins" }, hello: "Hi, {name}!" },
es: { menu: { start: "Empezar" }, coins: { one: "{count} moneda", other: "{count} monedas" } },
},
});
i18n.setLocale(i18n.detect()); // the player's browser language if you have it
i18n.t("menu.start"); // "Empezar"
i18n.t("coins", { count: 3 }); // "3 monedas"
i18n.t("hello", { name: "Sam" }); // falls back to English: "Hi, Sam!"
API
createI18n({ locales, fallback, locale }) → i18ni18n.t(key, vars) → stringdotted keys; {name} fills in vars; plural objects use vars.count; numbers in vars are formattedi18n.setLocale(code) → the code used (closest match: "es-MX" uses "es"); i18n.localei18n.detect(languages = navigator.languages) → best available codei18n.add(code, table)add or extend a language (merged)i18n.load(code, url, fetch) → Promiseload a JSON tablei18n.dir → "rtl" for Arabic, Hebrew, Persian and Urdu, else "ltr"i18n.number(n, options) / i18n.has(key)i18n.missing → Set of "code:key" asked for but not found (check it before release)i18n.onChange(fn) → offredraw text when the language changesi18n.apply(root)fill elements that have data-i18n=”key” and set lang and dir on root
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes. In canvas games, call t() when drawing text; in HTML menus use data-i18n and apply(). |
Tests
Node tests: nested keys, fill-ins, plurals for English, Russian and Arabic, fallback, missing list, closest match, detection, direction, merging, loading, apply().
Run them with node --test toolkit/components/localization-manager/ (Node 20 or newer, nothing to install).