### Install i18n-js Source: https://context7.com/fnando/i18n/llms.txt Install the i18n-js library using npm or yarn. ```bash npm install i18n-js # or yarn add i18n-js ``` -------------------------------- ### get(locale: string): string[] Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Locales.html Retrieves a list of locales to try for a given query, including inline options, current locale, and fallback locale. ```APIDOC ## get ### Description Return a list of all locales that must be tried before returning the missing translation message. By default, this will consider the inline option, current locale and fallback locale. ### Parameters #### Parameters - **locale** (string) - The locale query. ### Returns string[] The list of locales. ### Example ```javascript i18n.locales.get("de-DE");// ["de-DE", "de", "en"] ``` ``` -------------------------------- ### get Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Retrieves a value from the i18n scope based on a provided scope path. ```APIDOC ## get ### Description Retrieves a value from the i18n scope using a lookup path. ### Method `get(scope: Scope): any` ### Parameters * **scope** (Scope) - The scope lookup path. ### Returns any - The found scope value. ``` -------------------------------- ### Lazy Load Translations Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Asynchronously fetch and store translations for a given locale. This example uses the Fetch API. ```javascript import { I18n } from "i18n-js"; async function loadTranslations(i18n, locale) { const response = await fetch(`/translations/${locale}.json`); const translations = await response.json(); i18n.store(translations); } const i18n = new I18n(); loadTranslations(i18n, "es"); ``` -------------------------------- ### Register a Missing Translation Strategy Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/MissingTranslation.html Registers a new strategy for handling missing translations. This example shows how to register an 'oops' strategy that always returns a fixed phrase and then sets this strategy as the default behavior. ```javascript i18n.missingTranslation.register( "oops", (i18n, scope, options) => "Oops! Missing translation.");i18n.missingBehavior = "oops"; ``` -------------------------------- ### Translate messages with dynamic interpolation Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Interpolate dynamic values into translation strings. The example shows a greeting message that takes a name. ```javascript const i18n = new I18n({ en: { greetings: "Hi, %{name}!" }, "pt-BR": { greetings: "Olá, %{name}!" }, }); i18n.t("greetings", { name: "John" }); ``` -------------------------------- ### Define Translations with Pluralization Keywords Source: https://github.com/fnando/i18n/blob/main/README.md Define translations for different plural forms using keywords like 'zero', 'one', and 'other'. This is the default setup for English and similar languages. ```js const i18n = new I18n({ en: { inbox: { zero: "You have no messages", one: "You have one message", other: "You have %{count} messages", }, }, "pt-BR": { inbox: { zero: "Você não tem mensagens", one: "Você tem uma mensagem", other: "Você tem %{count} mensagens", }, }, }); ``` -------------------------------- ### Register Custom Pluralization Handler (Russian) Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Register a custom pluralization handler for languages with complex pluralization rules, such as Russian. This example defines rules for 'one', 'few', 'many', and 'other'. ```javascript i18n.pluralization.register("ru", (_i18n, count) => { const mod10 = count % 10; const mod100 = count % 100; let key; const one = mod10 === 1 && mod100 !== 11; const few = [2, 3, 4].includes(mod10) && ![12, 13, 14].includes(mod100); const many = mod10 === 0 || [5, 6, 7, 8, 9].includes(mod10) || [11, 12, 13, 14].includes(mod100); if (one) { key = "one"; } else if (few) { key = "few"; } else if (many) { key = "many"; } else { key = "other"; } return [key]; }); ``` -------------------------------- ### Configure Metro for .mjs Files Source: https://github.com/fnando/i18n/blob/main/README.md If encountering issues with `.mjs` files, update your Metro configuration to include them in `sourceExts`. This is often necessary for libraries like `make-plural`. ```javascript const { getDefaultConfig } = require("metro-config"); module.exports = (async () => { const { resolver: { assetExts, sourceExts }, } = await getDefaultConfig(); return { resolver: { sourceExts: [...sourceExts, "mjs"], }, }; })(); ``` -------------------------------- ### get Pluralizer Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Pluralization.html Retrieves the appropriate pluralizer function for a given locale, considering fallback mechanisms. ```APIDOC ## get(locale: string): Pluralizer ### Description Returns a list of possible pluralization keys for the given locale. It checks the explicitly set locale, the global i18n locale, and defaults to `defaultPluralizer`. ### Parameters #### Parameters - **locale** (string) - The locale for which to retrieve the pluralizer. ### Returns Pluralizer - The pluralizer function for the specified locale. ``` -------------------------------- ### I18n Constructor Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Initializes a new instance of the I18n class. You can provide initial translations and options to configure its behavior. ```APIDOC ## constructor ### Description Initializes a new instance of the I18n class. ### Parameters * **translations** (Dict) - Optional - Initial translations to load. * **options** (Partial) - Optional - Options to configure the I18n instance. ### Returns * I18n - A new instance of the I18n class. ``` -------------------------------- ### I18n#get Source: https://context7.com/fnando/i18n/llms.txt Retrieves the raw value at a specified scope in the translation store without any interpolation or pluralization. ```APIDOC ## `I18n#get(scope)` ### Description Returns the raw value at `scope` without any interpolation or pluralization. Useful for reading configuration objects or checking existence. ### Method Signature `get(scope: string): any` ### Parameters - **scope** (string) - The scope to retrieve the raw value from (e.g., `"en.messages.title"`). ### Returns - The raw value at the specified scope, or `undefined` if the scope does not exist. ### Request Example ```ts import { I18n } from "i18n-js"; const i18n = new I18n({ en: { number: { format: { delimiter: ",", separator: "." } } } }); i18n.get("number.format"); // { delimiter: ",", separator: "." } i18n.get("number.format.delimiter"); // "," i18n.get("does.not.exist"); // undefined ``` ``` -------------------------------- ### Create I18n Instance Source: https://context7.com/fnando/i18n/llms.txt Instantiate the I18n class with translations and configuration options. Options control locale, fallback, and missing translation behavior. ```typescript import { I18n } from "i18n-js"; const i18n = new I18n( { en: { hello: "Hello, %{name}!", inbox: { zero: "No messages", one: "1 message", other: "%{count} messages" }, number: { currency: { format: { unit: "$", precision: 2 } } }, }, "pt-BR": { hello: "Olá, %{name}!", inbox: { zero: "Sem mensagens", one: "1 mensagem", other: "%{count} mensagens" }, }, }, { locale: "en", defaultLocale: "en", enableFallback: true, missingBehavior: "message", // "message" | "guess" | "error" missingTranslationPrefix: "", defaultSeparator: ".", }, ); i18n.locale = "pt-BR"; console.log(i18n.locale); // "pt-BR" console.log(i18n.defaultLocale); // "en" console.log(i18n.version); // 2 (increments on each locale change or store update) ``` -------------------------------- ### new I18n(translations, options) Source: https://context7.com/fnando/i18n/llms.txt Instantiates the main I18n class with optional translations and configuration options. The translations object must be keyed by locale code, and options control locale, fallback, and missing translation behavior. ```APIDOC ## new I18n(translations, options) ### Description Instantiates the main `I18n` class with an optional translations object and configuration options. The `translations` object must be keyed by locale code at the root level. Options control the active locale, fallback behavior, missing-translation handling, and more. ### Parameters #### translations (object) - Optional An object where keys are locale codes and values are translation objects. #### options (object) - Optional Configuration options for the I18n instance. - **locale** (string) - The initial active locale. - **defaultLocale** (string) - The default locale to use if the active locale is not found. - **enableFallback** (boolean) - Whether to enable locale fallback. - **missingBehavior** (string) - How to handle missing translations. Options: "message", "guess", "error". - **missingTranslationPrefix** (string) - Prefix to add to missing translation keys. - **defaultSeparator** (string) - The separator used for nested translation keys. ### Request Example ```javascript import { I18n } from "i18n-js"; const i18n = new I18n( { en: { hello: "Hello, %{name}!", inbox: { zero: "No messages", one: "1 message", other: "%{count} messages" }, number: { currency: { format: { unit: "$", precision: 2 } } }, }, "pt-BR": { hello: "Olá, %{name}!", inbox: { zero: "Sem mensagens", one: "1 mensagem", other: "%{count} mensagens" }, }, }, { locale: "en", defaultLocale: "en", enableFallback: true, missingBehavior: "message", // "message" | "guess" | "error" missingTranslationPrefix: "", defaultSeparator: ".", }, ); i18n.locale = "pt-BR"; console.log(i18n.locale); // "pt-BR" console.log(i18n.defaultLocale); // "en" console.log(i18n.version); // 2 (increments on each locale change or store update) ``` ``` -------------------------------- ### Locales Constructor Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Locales.html Initializes a new instance of the Locales class. ```APIDOC ## constructor ### Description Initializes a new instance of the Locales class. ### Parameters #### Parameters - **i18n** ([I18n](I18n.html)) - The I18n instance to associate with this Locales object. ### Returns Locales A new Locales instance. ``` -------------------------------- ### Override interpolation function Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Override the default interpolation function to customize how dynamic values are handled, for example, to use React elements. ```javascript const i18n = new I18n({ en: { greetings: "Hi, %{name}!" }, "pt-BR": { greetings: "Olá, %{name}!" }, }); i18n.interpolate = (i18n, message, options) => { // ... }; return {i18n.t("greetings", { name: John })}; ``` -------------------------------- ### Registering a Pluralizer with make-plural Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Pluralization.html Shows how to register a custom pluralizer strategy for a locale, using the 'make-plural' library. This is useful for supporting languages with complex pluralization rules, like Russian. ```javascript import { ru } from "make-plural" import { useMakePlural } from "i18n-js" i18n.pluralization.register("ru", useMakePlural({ pluralizer: ru })); ``` -------------------------------- ### Pluralization Constructor Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Pluralization.html Initializes a new Pluralization instance, requiring an I18n instance. ```APIDOC ## new Pluralization(i18n: I18n) ### Description Initializes a new Pluralization instance. ### Parameters #### Parameters - **i18n** (I18n) - The I18n instance to associate with this pluralization manager. ### Returns Pluralization - A new Pluralization instance. ``` -------------------------------- ### Raw Translation Lookup with I18n#get Source: https://context7.com/fnando/i18n/llms.txt Returns the raw value at a scope without interpolation or pluralization. Useful for reading configuration or checking existence. ```typescript import { I18n } from "i18n-js"; const i18n = new I18n({ en: { number: { format: { delimiter: ",", separator: "." } } } }); i18n.get("number.format"); // { delimiter: ",", separator: "." } i18n.get("number.format.delimiter"); // "," i18n.get("does.not.exist"); // undefined ``` -------------------------------- ### Date and Time Formatting Utilities Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Provides direct access to date formatting functions like `toTime` and `strftime` for more granular control. ```APIDOC ## i18n.toTime() and i18n.strftime() ### Description Utility functions for direct date and time formatting. `toTime` formats a date input using a specified format string, while `strftime` formats a Date object using standard `strftime` directives. ### Method `i18n.toTime(formatString, dateInput)` `i18n.strftime(dateObject, formatDirectives)` ### Parameters - **toTime**: - **formatString** (string) - The key for the date/time format in the locale. - **dateInput** (string | number | Date) - The date/time value to format. - **strftime**: - **dateObject** (Date) - The Date object to format. - **formatDirectives** (string) - A string containing `strftime` format specifiers (e.g., "%d/%m/%Y"). ### `strftime` Format Directives - `%a`: Abbreviated weekday name (Sun) - `%A`: Full weekday name (Sunday) - `%b`: Abbreviated month name (Jan) - `%B`: Full month name (January) - `%c`: Preferred local date and time representation - `%d`: Day of the month (01..31) - `%H`: Hour of the day, 24-hour clock (00..23) - `%I`: Hour of the day, 12-hour clock (01..12) - `%m`: Month of the year (01..12) - `%M`: Minute of the hour (00..59) - `%p`: Meridian indicator (AM or PM) - `%S`: Second of the minute (00..60) - `%w`: Day of the week (Sunday is 0, 0..6) - `%y`: Year without a century (00..99) - `%Y`: Year with century - `%z`: Timezone offset (+0545) - `%Z`: Timezone name (e.g., PST) ### Request Example ```javascript const date = new Date(); i18n.toTime("date.formats.short", date); i18n.strftime(date, "%d/%m/%Y"); // => "18/09/2009" ``` ### Response - **string** - The formatted date or time string. ``` -------------------------------- ### Get Locale Resolution List Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Locales.html Retrieves a list of locales to try for a given query, including inline options, current locale, and fallback locale. ```javascript i18n.locales.get("de-DE");// ["de-DE", "de", "en"] ``` -------------------------------- ### onChange Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Adds a callback that is executed when locale or defaultLocale changes, or when I18n#store or I18n#update is called. ```APIDOC ## onChange ### Description Add a callback that will be executed whenever locale/defaultLocale changes, or `I18n#store` / `I18n#update` is called. ### Method Signature `onChange(callback: OnChangeHandler): () => void` ### Parameters * `callback` (OnChangeHandler): The callback that will be executed. ### Returns `() => void`: A function that can be used to unsubscribe the event handler. ### Example ```javascript const unsubscribe = i18n.onChange(() => { console.log('Locale or translations changed!'); }); // To unsubscribe later: unsubscribe(); ``` ``` -------------------------------- ### Register Custom Missing Translation Behavior Source: https://github.com/fnando/i18n/blob/main/README.md Register a new missing translation behavior using `i18n.missingTranslation.register()`. The example registers a behavior that returns an empty string. ```javascript i18n.missingTranslation.register("empty", (i18n, scope, options) => ""); // to use this, you can set `i18n.missingBehavior = "empty"` globally, or // by specifying the `missingBehavior` property when calling `i18n.t`. i18n.missingBehavior = "empty"; i18n.t("missing.key", { missingBehavior: "empty" }); ``` -------------------------------- ### Integrate with make-plural for Pluralization Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Integrate the 'make-plural' library to handle pluralization rules. Use the `useMakePlural` helper to wrap the pluralizer function. ```javascript import { ru } from "make-plural"; import { useMakePlural } from "i18n-js"; i18n.pluralization.register("ru", useMakePlural({ pluralizer: ru })); ``` -------------------------------- ### Integrate make-plural for Pluralization Rules Source: https://github.com/fnando/i18n/blob/main/README.md Integrate the 'make-plural' library to handle complex pluralization rules. This simplifies the process by wrapping the library's functions. ```js import { ru } from "make-plural"; import { useMakePlural } from "i18n-js"; i18n.pluralization.register("ru", useMakePlural({ pluralizer: ru })); ``` -------------------------------- ### Getting Pluralized Translations Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Pluralization.html Demonstrates how to use the i18n.t function to retrieve pluralized translations based on the 'count' option. Ensure the translation JSON includes keys for 'zero', 'one', and 'other'. ```javascript i18n.t("inbox", {count: 0}); // returns "You have no messages" i18n.t("inbox", {count: 1}); // returns "You have one message" i18n.t("inbox", {count: 2}); // returns "You have 2 messages" ``` -------------------------------- ### Convert List to Sentence Case Source: https://github.com/fnando/i18n/blob/main/README.md Use the `toSentence` helper to format a list of strings into a human-readable sentence with appropriate conjunctions and punctuation. ```javascript i18n.toSentence(["apple", "banana", "pineapple"]); //=> apple, banana, and pineapple. ``` -------------------------------- ### useMakePlural({ pluralizer, includeZero?, ordinal? }) Source: https://context7.com/fnando/i18n/llms.txt A utility factory that converts a `make-plural` locale function into an i18n-js-compatible `Pluralizer`. This function is exported directly from the package. ```APIDOC ## `useMakePlural({ pluralizer, includeZero?, ordinal? })` — Wrap a make-plural function A utility factory that converts a `make-plural` locale function into an i18n-js-compatible `Pluralizer`. Exported directly from the package. ```ts import { I18n, useMakePlural } from "i18n-js"; import { pl, ar } from "make-plural"; const i18n = new I18n({ pl: { items: { one: "% {count} element", few: "% {count} elementy", many: "% {count} elementów", other: "% {count} elementu" } }, ar: { items: { zero: "لا عناصر", one: "عنصر واحد", two: "عنصران", few: "% {count} عناصر", many: "% {count} عنصرًا", other: "% {count} عنصر" } }, }); i18n.pluralization.register("pl", useMakePlural({ pluralizer: pl })); i18n.pluralization.register("ar", useMakePlural({ pluralizer: ar, includeZero: true })); i18n.locale = "pl"; i18n.t("items", { count: 1 }); // => "1 element" i18n.t("items", { count: 5 }); // => "5 elementów" // Ordinal pluralization i18n.pluralization.register("en-ordinal", useMakePlural({ pluralizer: pl, ordinal: true })); ``` ``` -------------------------------- ### I18n#onChange Source: https://context7.com/fnando/i18n/llms.txt Subscribes a callback function to be executed whenever the store, locale, or defaultLocale changes. Returns a function to unsubscribe. ```APIDOC ## `I18n#onChange(callback)` ### Description Registers a callback that fires whenever `store()`, `update()`, `locale`, or `defaultLocale` changes. Returns an unsubscribe function. Also tracks changes via `i18n.version` (useful as a React dependency). ### Method Signature `onChange(callback: (instance: I18n) => void): () => void` ### Parameters - **callback** (function) - A function to be called when changes occur. It receives the I18n instance as an argument. ### Returns - A function that can be called to unsubscribe the callback. ### Request Example ```ts import { I18n } from "i18n-js"; import { useEffect, useState } from "react"; const i18n = new I18n({ en: { title: "Dashboard" } }); // Subscribe / unsubscribe const unsubscribe = i18n.onChange((instance) => { console.log("Locale changed to:", instance.locale); console.log("Version:", instance.version); }); i18n.locale = "fr"; // triggers callback unsubscribe(); // stops listening // React integration using version as a dependency key function useI18n() { const [, setVersion] = useState(i18n.version); useEffect(() => i18n.onChange(() => setVersion(i18n.version)), []); return i18n; } ``` ``` -------------------------------- ### Load and Use Base Locales in i18n-js Source: https://context7.com/fnando/i18n/llms.txt Import base locale JSON files and spread them into the I18n instance. Set the locale and use formatting functions like `l`, `numberToCurrency`, and `timeAgoInWords`. ```typescript import { I18n } from "i18n-js"; import en from "i18n-js/json/en.json"; import ptBR from "i18n-js/json/pt-BR.json"; import de from "i18n-js/json/de.json"; // Spread all base locales into the I18n instance const i18n = new I18n({ ...en, ...ptBR, ...de }); i18n.locale = "de"; i18n.l("currency", 1990.99); // "1.990,99 €" (German format) i18n.l("date.formats.short", "2024-06-15"); // locale-formatted German date i18n.locale = "pt-BR"; i18n.numberToCurrency(1990.99); // "R$ 1.990,99" i18n.timeAgoInWords( new Date(Date.now() - 3600000), new Date(), ); // "aproximadamente 1 hora" ``` -------------------------------- ### Subscribe to Changes with I18n#onChange Source: https://context7.com/fnando/i18n/llms.txt Registers a callback that fires on store or locale changes. Returns an unsubscribe function and tracks changes via `i18n.version`. ```typescript import { I18n } from "i18n-js"; import { useEffect, useState } from "react"; const i18n = new I18n({ en: { title: "Dashboard" } }); // Subscribe / unsubscribe const unsubscribe = i18n.onChange((instance) => { console.log("Locale changed to:", instance.locale); console.log("Version:", instance.version); }); i18n.locale = "fr"; // triggers callback unsubscribe(); // stops listening // React integration using version as a dependency key function useI18n() { const [, setVersion] = useState(i18n.version); useEffect(() => i18n.onChange(() => setVersion(i18n.version)), []); return i18n; } ``` -------------------------------- ### version (getter) Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Returns the current change version of the i18n instance. This version increments on locale changes or translation updates. ```APIDOC ## version ### Description Returns the change version. This value is incremented whenever `I18n#store` or `I18n#update` is called, or when `I18n#locale`/`I18n#defaultLocale` is set. ### Getter * **Returns**: number - The current change version. * **Usage**: `const version = i18n.version;` ``` -------------------------------- ### store Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Updates translations by merging them. New translations override existing ones. ```APIDOC ## store ### Description Update translations by merging them. Newest translations will override existing ones. ### Method Signature `store(translations: Dict): void` ### Parameters * `translations` (Dict): An object containing the translations that will be merged into existing translations. ### Returns void ### Example ```javascript i18n.store({ en: { messages: { welcome: 'Welcome!' } } }); i18n.t('messages.welcome'); // => "Welcome!" i18n.store({ en: { messages: { welcome: 'Hello!' // Overrides the previous welcome message } } }); i18n.t('messages.welcome'); // => "Hello!" ``` ``` -------------------------------- ### register(locale: string, localeResolver: string | string[] | LocaleResolver): void Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/Locales.html Registers a custom locale resolution strategy for a given locale. ```APIDOC ## register ### Description You can define custom rules for any locale. Just make sure you return an array containing all locales. ### Parameters #### Parameters - **locale** (string) - The locale's name. - **localeResolver** (string | string[] | [LocaleResolver](../types/LocaleResolver.html)) - The locale resolver strategy. ### Returns void ### Example ```javascript // Default the Wookie locale to English. i18n.locales.register("wk", (_i18n, locale) => { return ["en"];}); ``` ``` -------------------------------- ### I18n#toSentence Source: https://context7.com/fnando/i18n/llms.txt Joins an array of items into a comma-separated sentence with a configurable connector word before the last item. Connector defaults are read from `support.array` in the translation store. ```APIDOC ## `I18n#toSentence(items, options?)` ### Description Joins an array of items into a comma-separated sentence with a configurable connector word before the last item. Connector defaults are read from `support.array` in the translation store. ### Parameters #### Path Parameters - **items** (Array) - Required - The array of items to join. #### Options - **wordsConnector** (string) - Optional - The connector for items before the last one. - **lastWordConnector** (string) - Optional - The connector for the last item. - **twoWordsConnector** (string) - Optional - The connector for exactly two items. ### Request Example ```javascript import { I18n } from "i18n-js"; const i18n = new I18n(); i18n.toSentence([]); // => "" i18n.toSentence(["apple"]); // => "apple" i18n.toSentence(["apple", "banana"]); // => "apple and banana" i18n.toSentence(["apple", "banana", "pineapple"]); // => "apple, banana, and pineapple." // Custom connectors i18n.toSentence(["red", "green", "blue"], { wordsConnector: " + ", lastWordConnector: " + ", }); // => "red + green + blue" ``` ``` -------------------------------- ### Properties of StrftimeOptions Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/interfaces/StrftimeOptions.html Detailed breakdown of each property within the StrftimeOptions interface. ```APIDOC ### abbrDayNames abbrDayNames: DayNames ### abbrMonthNames abbrMonthNames: MonthNames ### dayNames dayNames: DayNames ### meridian meridian: { am: string; pm: string } ### monthNames monthNames: MonthNames ### utc (Optional) utc?: boolean ``` -------------------------------- ### MissingTranslation Constructor Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/MissingTranslation.html Initializes a new instance of the MissingTranslation class. ```APIDOC ## constructor ### Description Initializes a new instance of the MissingTranslation class. ### Parameters * **i18n** ([I18n](../I18n.html)) - The I18n instance. ### Returns * MissingTranslation ``` -------------------------------- ### Initialize I18n with Translations Source: https://github.com/fnando/i18n/blob/main/README.md Instantiate the I18n class with a translations object. This object can be imported from a JSON file or defined directly. ```javascript import { I18n } from "i18n-js"; import translations from "./translations.json"; const i18n = new I18n(translations); ``` ```javascript const i18n = new I18n({ en: { hello: "Hi!", }, "pt-BR": { hello: "Olá!", }, }); ``` -------------------------------- ### Localized Number and Currency Formatting Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Format numbers and currency according to the current locale using the `l` helper. This provides localized output similar to Rails helpers. ```javascript i18n.l("currency", 1990.99);// $1,990.99 i18n.l("number", 1990.99);// 1,990.99 i18n.l("percentage", 123.45);// 123.450% ``` -------------------------------- ### Configure Metro Bundler for .mjs Files Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Modify your Metro configuration to include `.mjs` files, which is necessary for libraries like `make-plural` when using React Native. ```javascript const { getDefaultConfig } = require("metro-config"); module.exports = (async () => { const { resolver: { assetExts, sourceExts }, } = await getDefaultConfig(); return { resolver: { sourceExts: [...sourceExts, "mjs"], }, }; })(); ``` -------------------------------- ### StrftimeOptions Interface Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/interfaces/StrftimeOptions.html This interface outlines the available properties for configuring strftime formatting, including day and month names, and meridian indicators. ```APIDOC interface StrftimeOptions { abbrDayNames: DayNames; abbrMonthNames: MonthNames; dayNames: DayNames; meridian: { am: string; pm: string }; monthNames: MonthNames; utc?: boolean; } ``` -------------------------------- ### Run Code in Temporary Locale with I18n#withLocale Source: https://context7.com/fnando/i18n/llms.txt Asynchronously switches the locale for the duration of a callback and restores the original locale afterward. Safe with async callbacks. ```typescript import { I18n } from "i18n-js"; const i18n = new I18n({ en: { greeting: "Hello" }, es: { greeting: "Hola" }, }); i18n.locale = "en"; console.log(i18n.t("greeting")); // "Hello" await i18n.withLocale("es", async () => { console.log(i18n.t("greeting")); // "Hola" await someAsyncWork(); }); console.log(i18n.t("greeting")); // "Hello" – restored ``` -------------------------------- ### Date and Time Localization Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Formats dates and times according to locale-specific settings, supporting various input formats and custom placeholders. ```APIDOC ## i18n.l() / i18n.localize() ### Description Localizes dates and times using predefined or custom format strings. Accepts various input types including strings, epoch timestamps, and Date objects. ### Method `i18n.l(formatString, dateInput, [options])` or `i18n.localize(formatString, dateInput, [options])` ### Parameters - **formatString** (string) - The key for the date/time format in the locale (e.g., "date.formats.short"). - **dateInput** (string | number | Date) - The date/time value to format. Can be in formats like 'yyyy-mm-dd', 'yyyy-mm-dd hh:mm:ss', ISO 8601, epoch milliseconds, or a `Date` object. - **options** (object) - Optional object for placeholders within the format string. - **{key: value}** - Placeholders to be interpolated into the format string (e.g., `{ day: "18th" }`). ### Request Example ```javascript i18n.l("date.formats.short", "2009-09-18"); // => "09/18/2009" i18n.l("time.formats.short", "2009-09-18 23:12:43"); // => "11/09/2009 11:12:43 PM" i18n.l("date.formats.ordinalDay", "2009-09-18", { day: "18th" }); // => "September 18th" ``` ### Response - **string** - The formatted date or time string. ``` -------------------------------- ### Format number as percentage Source: https://context7.com/fnando/i18n/llms.txt Converts a number to a percentage string. Defaults are read from the store, and options can customize precision and formatting. ```typescript import { I18n } from "i18n-js"; const i18n = new I18n(); i18n.numberToPercentage(100); // => "100.000%" i18n.numberToPercentage(100, { precision: 0 }); // => "100%" i18n.numberToPercentage(1000, { delimiter: ".", separator: "," }); // => "1.000.000%" i18n.numberToPercentage(302.24398, { precision: 5, roundMode: "down" }); // => "302.24398%" i18n.numberToPercentage(100, { format: "%n %" }); // => "100.000 %" ``` -------------------------------- ### I18n#numberToPercentage Source: https://context7.com/fnando/i18n/llms.txt Converts a number to a percentage string. Reads defaults from `number.format` and `number.percentage.format` in the store. ```APIDOC ## `I18n#numberToPercentage(input, options?)` — Format as percentage Converts a number to a percentage string. Reads defaults from `number.format` and `number.percentage.format` in the store. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript import { I18n } from "i18n-js"; const i18n = new I18n(); i18n.numberToPercentage(100); // => "100.000%" i18n.numberToPercentage(100, { precision: 0 }); // => "100%" i18n.numberToPercentage(1000, { delimiter: ".", separator: "," }); // => "1.000.000%" i18n.numberToPercentage(302.24398, { precision: 5, roundMode: "down" }); // => "302.24398%" i18n.numberToPercentage(100, { format: "%n %" }); // => "100.000 %" ``` ### Response #### Success Response (200) - None explicitly defined, but returns a formatted string. #### Response Example ```json { "example": "100.000%" } ``` ``` -------------------------------- ### toSentence Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Converts an array of items into a human-readable sentence, joining elements with specified connectors. ```APIDOC ## toSentence ### Description Converts the array to a comma-separated sentence where the last element is joined by the connector word. ### Parameters * **items** (any[]) - The list of items that will be joined. * **options** (Partial) - Optional. The options. * `wordsConnector`: The sign or word used to join the elements in arrays with two or more elements (default: ", "). * `twoWordsConnector`: The sign or word used to join the elements in arrays with two elements (default: " and "). * `lastWordConnector`: The sign or word used to join the last element in arrays with three or more elements (default: ", and "). ### Returns string The joined string. ### Example ```javascript i18n.toSentence(["apple", "banana", "pineapple"]);//=> apple, banana, and pineapple. ``` ``` -------------------------------- ### Localized Number and Currency Formatting Source: https://github.com/fnando/i18n/blob/main/README.md Perform localized number and currency formatting using the 'l' method. This helper function formats numbers according to the current locale's conventions. ```js i18n.l("currency", 1990.99); // $1,990.99 i18n.l("number", 1990.99); // 1,990.99 i18n.l("percentage", 123.45); // 123.450% ``` -------------------------------- ### Load Base Translations Source: https://github.com/fnando/i18n/blob/main/README.md Load base translations for formatting dates, numbers, and other common elements by importing JSON files provided by the library. ```javascript import { I18n } from "i18n-js"; import ptBR from "i18n-js/json/pt-BR.json"; import en from "i18n-js/json/en.json"; const i18n = new I18n({ ...ptBR, ...en, }); ``` -------------------------------- ### Join Array to Sentence with I18n#toSentence Source: https://context7.com/fnando/i18n/llms.txt Joins array items into a natural-language sentence, using configurable connectors for items and the last item. Defaults are read from `support.array` in the translation store. ```typescript import { I18n } from "i18n-js"; const i18n = new I18n(); i18n.toSentence([]); // => "" ``` ```typescript i18n.toSentence(["apple"]); // => "apple" ``` ```typescript i18n.toSentence(["apple", "banana"]); // => "apple and banana" ``` ```typescript i18n.toSentence(["apple", "banana", "pineapple"]); // => "apple, banana, and pineapple." ``` ```typescript // Custom connectors i18n.toSentence(["red", "green", "blue"], { wordsConnector: " + ", lastWordConnector: " + ", }); // => "red + green + blue" ``` -------------------------------- ### Format Number to Currency Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/index.html Format a number into a currency string using `I18n#numberToCurrency`. Options can customize precision, unit, delimiters, and formatting. ```javascript i18n.numberToCurrency(1990.99, { unit: "$", precision: 2, delimiter: ",", separator: "." }); ``` -------------------------------- ### Convert Number to Percentage String Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Use this method to format a number as a percentage string. Options can be provided to customize precision, rounding, separators, delimiters, and formats for positive and negative numbers. If precision is null, insignificant zeros are not stripped. ```typescript i18n.numberToPercentage(100); // => "100.000%" ``` ```typescript i18n.numberToPercentage("98"); // => "98.000%" ``` ```typescript i18n.numberToPercentage(100, { precision: 0 }); // => "100%" ``` ```typescript i18n.numberToPercentage(1000, { delimiter: ".", separator: "," }); // => "1.000,000%" ``` ```typescript i18n.numberToPercentage(302.24398923423, { precision: 5 }); // => "302.24399%" ``` ```typescript i18n.numberToPercentage(1000, { precision: null }); // => "1000%" ``` ```typescript i18n.numberToPercentage("98a"); // => "98a%" ``` ```typescript i18n.numberToPercentage(100, { format: "%n %" }); // => "100.000 %" ``` ```typescript i18n.numberToPercentage(302.24398923423, { precision: 5, roundMode: "down" }); // => "302.24398%" ``` -------------------------------- ### Format Bytes to Human-Readable Size Source: https://github.com/fnando/i18n/blob/main/README.md Use `numberToHumanSize` to convert byte counts into human-readable strings like KB, MB, GB. Customize precision, rounding, and separators. ```javascript i18n.numberToHumanSize(123) // => "123 Bytes" i18n.numberToHumanSize(1234) // => "1.21 KB" i18n.numberToHumanSize(12345) // => "12.1 KB" i18n.numberToHumanSize(1234567) // => "1.18 MB" i18n.numberToHumanSize(1234567890) // => "1.15 GB" i18n.numberToHumanSize(1234567890123) // => "1.12 TB" i18n.numberToHumanSize(1234567890123456) // => "1.1 PB" i18n.numberToHumanSize(1234567890123456789) // => "1.07 EB" i18n.numberToHumanSize(1234567, {precision: 2}) // => "1.2 MB" i18n.numberToHumanSize(483989, precision: 2) // => "470 KB" i18n.numberToHumanSize(483989, {precision: 2, roundMode: "up"}) // => "480 KB" i18n.numberToHumanSize(1234567, {precision: 2, separator: ","}) // => "1,2 MB" i18n.numberToHumanSize(1234567890123, {precision: 5}) // => "1.1228 TB" i18n.numberToHumanSize(524288000, {precision: 5}) // => "500 MB" ``` -------------------------------- ### withLocale Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Executes a function with a given locale set temporarily. The locale reverts to its previous value after the callback finishes, whether it succeeds or fails. This is an asynchronous operation and requires `await`. ```APIDOC ## withLocale ### Description Executes function with given locale set. The locale will be changed only during the `callback`'s execution, switching back to the previous value once it finishes (with or without errors). This is an asynchronous call, which means you must use `await` or you may end up with a race condition. ### Method Signature withLocale(locale: string, callback: () => void): Promise ### Parameters #### locale - **locale** (string) - Required - The temporary locale that will be set during the function's execution. #### callback - **callback** (() => void) - Required - The function that will be executed with a temporary locale set. ### Returns - **Promise** ### Example ```javascript await i18n.withLocale("pt", () => { console.log(i18n.t("hello"));}); ``` ``` -------------------------------- ### I18n#toTime Source: https://context7.com/fnando/i18n/llms.txt Looks up a date/time format string from the translation store by `scope`, parses `input` (string, epoch number, or Date), and returns a formatted string via `strftime`. ```APIDOC ## `I18n#toTime(scope, input)` ### Description Looks up a date/time format string from the translation store by `scope`, parses `input` (string, epoch number, or Date), and returns a formatted string via `strftime`. ### Parameters #### Path Parameters - **scope** (string) - Required - The translation scope for the date format. - **input** (string | number | Date) - Required - The date input (string, epoch milliseconds, or Date object). ### Request Example ```javascript import { I18n } from "i18n-js"; import en from "i18n-js/json/en.json"; const i18n = new I18n({ ...en }); // yyyy-mm-dd string i18n.toTime("date.formats.short", "2024-06-15"); // Epoch milliseconds i18n.toTime("date.formats.long", 1718448000000); // Date object i18n.toTime("time.formats.short", new Date()); // ISO 8601 UTC i18n.toTime("time.formats.long", "2024-06-15T18:10:34Z"); ``` ``` -------------------------------- ### localize Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Localizes various data types (string, number, Date) into a human-readable string format based on the provided type and options. ```APIDOC ## localize ### Description Localizes values such as currency, numbers, percentages, dates, and times into a string format. ### Method `localize(type: string, value: string | number | Date | null | undefined, options?: Dict): string` ### Parameters * **type** (string) - The localization type (e.g., `currency`, `number`, `percentage`, `date`, `time`). * **value** (string | number | Date | null | undefined) - The value to be localized. Returns an empty string if `null` or `undefined`. * **options** (Dict) - Optional. Localization options. ### Returns string - The localized string. ``` -------------------------------- ### ToSentenceOptions Interface Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/interfaces/ToSentenceOptions.html The ToSentenceOptions interface defines the available options for customizing how an array of words is converted into a sentence. You can specify different connectors for words, two words, and the last word. ```APIDOC interface ToSentenceOptions { wordsConnector: string; twoWordsConnector: string; lastWordConnector: string; } ``` -------------------------------- ### locale (getter/setter) Source: https://github.com/fnando/i18n/blob/main/docs/v4.5.3/classes/I18n.html Manages the current locale. It can be explicitly set or fallback to the default locale or 'en'. ```APIDOC ## locale ### Description Manages the current locale for translations. ### Getter * **Returns**: string - The current locale. * **Usage**: `const locale = i18n.locale;` ### Setter * **Parameters**: * **newLocale**: string - The new locale to set. * **Returns**: void * **Usage**: `i18n.locale = 'es';` ```