A map of language codes to translation objects. Keys are matched case- and separator-insensitively, so ru_RU and ru-RU are equivalent.
Optionaloptions: { fallback?: string; language?: string }
Configuration options.
Optionalfallback?: stringFallback language code when the default is unavailable; defaults to "en". Resolved case- and separator-insensitively; a regional code such as "en-US" (or "en_US") uses the "en" translations when it has no entry of its own.
Optionallanguage?: stringDefault language code; defaults to the browser language. Resolved case- and separator-insensitively; a regional code such as "ru-RU" (or "ru_RU") uses the "ru" translations when it has no entry of its own.
A translation function. Missing keys, fallback misses, and keys naming a nested group instead of a string return the key itself. Each such key is also reported once per locale through reportError (or console.error where it is unavailable).
const t = i18n({
en: {
say: { hello: "Hello, %{name}!" },
speed: "Speed: %{value}",
birthday: "Birthday: %{date}",
},
de: {
say: { hello: "Hallo, %{name}!" },
speed: "Geschwindigkeit: %{value}",
birthday: "Geburtstag: %{date}",
},
});
// text with variables
t("say.hello", { name: "Alice" }); // Hello, Alice!
// explicitly specified locale
t("say.hello", { name: "Emma" }, "de"); // Hallo, Emma!
// Intl.NumberFormat
t("speed", { value: [15, { style: "unit", unit: "kilometer-per-hour" }] }); // Speed: 15 km/h
t(1234, { style: "currency", currency: "USD" }); // $1,234.00
// Intl.DateTimeFormat
t("birthday", { date: [new Date(2021, 0, 1), { dateStyle: "short" }] }); // Birthday: 1/1/21
t(new Date(2021, 0, 1), { dateStyle: "full" }); // Friday, January 1, 2021
Creates a translation function.
The returned function resolves a translation string by dot-separated path (or a flat key), interpolates
%{key}-style placeholders from a data object, and formats a non-string first argument directly viatoLocaleString.A requested language is matched case- and separator-insensitively to an exact locale key, or — when there is none — to the nearest one: the longest key the language starts with at a subtag boundary (
ru-RUmatchesru, andzh-Hant-TWmatcheszh-Hant, butrun-BIdoes not matchru).Formatting follows the language the result comes from: a language with translations (an exact entry, or its base such as
ruforru-RU) formats with its full code; a language without an entry, and a key found only in the fallback, format with the fallback instead, so a value never mixes one language's text with another's formatting.Language-sensitive formatting: