i18n-js
- Version 4.5.1
- Published
- 1.7 MB
- 3 dependencies
- MIT license
Install
npm i i18n-js
yarn add i18n-js
pnpm add i18n-js
Overview
A small library to provide I18n on JavaScript.
Index
Functions
Classes
I18n
- defaultLocale
- defaultSeparator
- distanceOfTimeInWords
- enableFallback
- formatNumber()
- get()
- interpolate
- l
- locale
- locales
- localize()
- missingBehavior
- missingPlaceholder
- missingTranslation
- missingTranslationPrefix
- nullPlaceholder
- numberToCurrency()
- numberToDelimited()
- numberToHuman()
- numberToHumanSize()
- numberToPercentage()
- numberToRounded()
- onChange()
- onChangeHandlers
- p
- placeholder
- pluralization
- pluralize()
- store()
- strftime()
- t
- timeAgoInWords()
- toSentence()
- toTime()
- transformKey
- translate()
- translations
- update()
- version
- withLocale()
Interfaces
Type Aliases
- AnyObject
- ArrayType
- DateTime
- DayNames
- LocaleResolver
- MakePlural
- MissingBehavior
- MissingPlaceholderHandler
- MissingTranslationStrategy
- MonthNames
- NullPlaceholderHandler
- NumberToCurrencyOptions
- NumberToDelimitedOptions
- NumberToHumanOptions
- NumberToHumanSizeOptions
- NumberToHumanUnits
- NumberToPercentageOptions
- NumberToRoundedOptions
- Numeric
- OnChangeHandler
- Pluralizer
- PrimitiveType
- RoundingMode
- Scope
Functions
function useMakePlural
useMakePlural: ({ pluralizer, includeZero, ordinal,}: { pluralizer: MakePlural; includeZero?: boolean; ordinal?: boolean;}) => Pluralizer;
Creates a new pluralizer function based on [make-plural](https://github.com/eemeli/make-plural/tree/master/packages/plurals).
Parameter
{boolean} options.includeZero When
true
, will returnzero
as the first key for0
pluralization.Parameter
{boolean} options.ordinal When
true
, will return the scope based on make-plural's ordinal category.Parameter
{MakePlural} options.pluralizer The make-plural function that will be wrapped. {Pluralizer} Returns a pluralizer that can be used by I18n.
Classes
class I18n
class I18n {}
constructor
constructor(translations?: Dict, options?: Partial<I18nOptions>);
property defaultLocale
defaultLocale: string;
Return the default locale, using a explicit locale set using
i18n.defaultLocale = locale
, the default locale set usingi18n.defaultLocale
or the fallback, which isen
.Returns
{string} The current locale.
property defaultSeparator
defaultSeparator: string;
Set the default string separator. Defaults to
.
, as inscope.translation
.{string}
property distanceOfTimeInWords
distanceOfTimeInWords: ( fromTime: DateTime, toTime: DateTime, options?: TimeAgoInWordsOptions) => string;
property enableFallback
enableFallback: boolean;
Set if engine should fallback to the default locale when a translation is missing. Defaults to
false
.When enabled, missing translations will first be looked for in less specific versions of the requested locale and if that fails by taking them from your
I18n#defaultLocale
.{boolean}
property interpolate
interpolate: (i18n: I18n, message: string, options: TranslateOptions) => string;
Override the interpolation function. For the default implementation, see <https://github.com/fnando/i18n/tree/main/src/helpers/interpolate.ts> {(i18n: I18n, message: string, options: TranslateOptions) => string}
property l
l: (type: string, value: string | number | Date, options?: Dict) => string;
property locale
locale: string;
Return the current locale, using a explicit locale set using
i18n.locale = newLocale
, the default locale set usingi18n.defaultLocale
or the fallback, which isen
.Returns
{string} The current locale.
property locales
locales: Locales;
The locale resolver registry.
See Also
{Locales}
property missingBehavior
missingBehavior: string;
Set missing translation behavior.
-
message
will display a message that the translation is missing. -guess
will try to guess the string. -error
will raise an exception whenever a translation is not defined.See MissingTranslation.register for instructions on how to define your own behavior.
{MissingBehavior}
property missingPlaceholder
missingPlaceholder: MissingPlaceholderHandler;
Return a missing placeholder message for given parameters.
{MissingPlaceholderHandler}
property missingTranslation
missingTranslation: MissingTranslation;
The missing translation behavior registry.
See Also
{MissingTranslation}
property missingTranslationPrefix
missingTranslationPrefix: string;
If you use missingBehavior with 'message', but want to know that the string is actually missing for testing purposes, you can prefix the guessed string by setting the value here. By default, no prefix is used.
{string}
property nullPlaceholder
nullPlaceholder: NullPlaceholderHandler;
Return a placeholder message for null values. Defaults to the same behavior as
I18n.missingPlaceholder
.{NullPlaceholderHandler}
property onChangeHandlers
onChangeHandlers: OnChangeHandler[];
List of all onChange handlers.
{OnChangeHandler[]}
property p
p: (count: number, scope: Scope, options?: TranslateOptions) => string;
property placeholder
placeholder: RegExp;
Set the placeholder format. Accepts
{{placeholder}}
and%{placeholder}
.{RegExp}
property pluralization
pluralization: Pluralization;
The pluralization behavior registry.
See Also
{Pluralization}
property t
t: <T = string>(scope: Scope, options?: TranslateOptions) => string | T;
property transformKey
transformKey: (key: string) => string;
Transform keys. By default, it returns the key as it is, but allows for overriding. For instance, you can set a function to receive the camelcase key, and convert it to snake case.
{(key: string) => string}
property translations
translations: Dict;
Set the registered translations. The root key must always be the locale (and its variations with region).
Remember that no events will be triggered if you change this object directly. To trigger
onchange
events, you must perform updates either usingI18n#store
orI18n#update
.{Dict}
property version
readonly version: number;
Return the change version. This value is incremented whenever
I18n#store
orI18n#update
is called, or whenI18n#locale
/I18n#defaultLocale
is set.
method formatNumber
formatNumber: (input: Numeric, options?: Partial<FormatNumberOptions>) => string;
Formats a number.
Parameter input
The numeric value that will be formatted.
Parameter options
The formatting options. Defaults to: `{ delimiter: ",", precision: 3, separator: ".", unit: "", format: "%u%n", significant: false, stripInsignificantZeros: false, }` {string} The formatted number.
method get
get: (scope: Scope) => any;
Parameter scope
The scope lookup path.
Returns
{any} The found scope.
method localize
localize: ( type: string, value: string | number | Date | null | undefined, options?: Dict) => string;
Localize several values.
You can provide the following scopes:
currency
,number
, orpercentage
. If you provide a scope that matches the/^(date|time)/
regular expression then thevalue
will be converted by using theI18n.toTime
function. It will default to the value'stoString
function.If value is either
null
orundefined
then an empty string will be returned, regardless of what localization type has been used.Parameter type
The localization type.
Parameter value
The value that must be localized.
Parameter options
The localization options.
Returns
{string} The localized string.
method numberToCurrency
numberToCurrency: ( input: Numeric, options?: Partial<NumberToCurrencyOptions>) => string;
Formats a
number
into a currency string (e.g., $13.65). You can customize the format in the using anoptions
object.The currency unit and number formatting of the current locale will be used unless otherwise specified in the provided options. No currency conversion is performed. If the user is given a way to change their locale, they will also be able to change the relative value of the currency displayed with this helper.
Parameter input
The number to be formatted.
Parameter options
The formatting options. When defined, supersedes the default options defined by
number.format
andnumber.currency.*
.Parameter
{number} options.precision Sets the level of precision (defaults to 2).
Parameter
{RoundingMode} options.roundMode Determine how rounding is performed (defaults to
default
.)Parameter
{string} options.unit Sets the denomination of the currency (defaults to "$").
Parameter
{string} options.separator Sets the separator between the units (defaults to ".").
Parameter
{string} options.delimiter Sets the thousands delimiter (defaults to ",").
Parameter
{string} options.format Sets the format for non-negative numbers (defaults to "%u%n"). Fields are
%u
for the currency, and%n
for the number.Parameter
{string} options.negativeFormat Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by
format
). Accepts the same fields thanformat
, except%n
is here the absolute value of the number.Parameter
{boolean} options.stripInsignificantZeros If
true
removes insignificant zeros after the decimal separator (defaults tofalse
).Parameter
{boolean} options.raise If
true
, raises exception for non-numeric values likeNaN
and infinite values.Returns
{string} The formatted number.
Example 1
i18n.numberToCurrency(1234567890.5);// => "$1,234,567,890.50"i18n.numberToCurrency(1234567890.506);// => "$1,234,567,890.51"i18n.numberToCurrency(1234567890.506, { precision: 3 });// => "$1,234,567,890.506"i18n.numberToCurrency("123a456");// => "$123a456"i18n.numberToCurrency("123a456", { raise: true });// => raises exception ("123a456" is not a valid numeric value)i18n.numberToCurrency(-0.456789, { precision: 0 });// => "$0"i18n.numberToCurrency(-1234567890.5, { negativeFormat: "(%u%n)" });// => "($1,234,567,890.50)"i18n.numberToCurrency(1234567890.5, {unit: "£",separator: ",",delimiter: "",});// => "£1234567890,50"i18n.numberToCurrency(1234567890.5, {unit: "£",separator: ",",delimiter: "",format: "%n %u",});// => "1234567890,50 £"i18n.numberToCurrency(1234567890.5, { stripInsignificantZeros: true });// => "$1,234,567,890.5"i18n.numberToCurrency(1234567890.5, { precision: 0, roundMode: "up" });// => "$1,234,567,891"
method numberToDelimited
numberToDelimited: ( input: Numeric, options?: Partial<NumberToDelimitedOptions>) => string;
Formats a +number+ with grouped thousands using
delimiter
(e.g., 12,324). You can customize the format in theoptions
parameter.Parameter input
The numeric value that will be formatted.
Parameter options
The formatting options.
Parameter
{string} options.delimiter Sets the thousands delimiter (defaults to ",").
Parameter
{string} options.separator Sets the separator between the fractional and integer digits (defaults to ".").
Parameter
{RegExp} options.delimiterPattern Sets a custom regular expression used for deriving the placement of delimiter. Helpful when using currency formats like INR.
{string} The formatted number.
Example 1
i18n.numberToDelimited(12345678);// => "12,345,678"i18n.numberToDelimited("123456");// => "123,456"i18n.numberToDelimited(12345678.05);// => "12,345,678.05"i18n.numberToDelimited(12345678, { delimiter: "." });// => "12.345.678"i18n.numberToDelimited(12345678, { delimiter: "," });// => "12,345,678"i18n.numberToDelimited(12345678.05, { separator: " " });// => "12,345,678 05"i18n.numberToDelimited("112a");// => "112a"i18n.numberToDelimited(98765432.98, { delimiter: " ", separator: "," });// => "98 765 432,98"i18n.numberToDelimited("123456.78", {delimiterPattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/g,});// => "1,23,456.78"
method numberToHuman
numberToHuman: ( input: Numeric, options?: Partial<NumberToHumanOptions>) => string;
Convert a number into a readable representation.
Parameter input
The number that will be formatted.
Parameter options
The formatting options. When defined, supersedes the default options stored at
number.human.format.*
andnumber.human.storage_units.*
.Parameter
{number} options.precision Sets the precision of the number (defaults to 3).
Parameter
{RoundingMode} options.roundMode Determine how rounding is performed (defaults to
default
).Parameter
{boolean} options.significant If
true
, precision will be the number of significant_digits. Iffalse
, the number of fractional digits (defaults totrue
)Parameter
{string} options.separator Sets the separator between the fractional and integer digits (defaults to ".").
Parameter
{string} options.delimiter Sets the thousands delimiter (defaults to "").
Parameter
{boolean} options.stripInsignificantZeros If
true
removes insignificant zeros after the decimal separator (defaults totrue
).Parameter
{Dict} options.units A Hash of unit quantifier names. Or a string containing an I18n scope where to find this object. It might have the following keys:
- _integers_:
unit
,ten
,hundred
,thousand
,million
,billion
,trillion
,quadrillion
- _fractionals_:deci
,centi
,mili
,micro
,nano
,pico
,femto
Parameter
{string} options.format Sets the format of the output string (defaults to "%n %u"). The field types are:
-
%u
- The quantifier (ex.: 'thousand') -%n
- The numberReturns
{string} The formatted number.
Example 1
i18n.numberToHuman(123);// => "123"i18n.numberToHuman(1234);// => "1.23 Thousand"i18n.numberToHuman(12345);// => "12.3 Thousand"i18n.numberToHuman(1234567);// => "1.23 Million"i18n.numberToHuman(1234567890);// => "1.23 Billion"i18n.numberToHuman(1234567890123);// => "1.23 Trillion"i18n.numberToHuman(1234567890123456);// => "1.23 Quadrillion"i18n.numberToHuman(1234567890123456789);// => "1230 Quadrillion"i18n.numberToHuman(489939, { precision: 2 });// => "490 Thousand"i18n.numberToHuman(489939, { precision: 4 });// => "489.9 Thousand"i18n.numberToHuman(489939, { precision: 2, roundMode: "down" });// => "480 Thousand"i18n.numberToHuman(1234567, { precision: 4, significant: false });// => "1.2346 Million"i18n.numberToHuman(1234567, {precision: 1,separator: ",",significant: false,});// => "1,2 Million"i18n.numberToHuman(500000000, { precision: 5 });// => "500 Million"i18n.numberToHuman(12345012345, { significant: false });// => "12.345 Billion"Non-significant zeros after the decimal separator are stripped out by default (set
stripInsignificantZeros
tofalse
to change that):i18n.numberToHuman(12.00001);// => "12"i18n.numberToHuman(12.00001, { stripInsignificantZeros: false });// => "12.0"You can also use your own custom unit quantifiers:
i18n.numberToHuman(500000, units: { unit: "ml", thousand: "lt" });// => "500 lt"If in your I18n locale you have:
---en:distance:centi:one: "centimeter"other: "centimeters"unit:one: "meter"other: "meters"thousand:one: "kilometer"other: "kilometers"billion: "gazillion-distance"Then you could do:
i18n.numberToHuman(543934, { units: "distance" });// => "544 kilometers"i18n.numberToHuman(54393498, { units: "distance" });// => "54400 kilometers"i18n.numberToHuman(54393498000, { units: "distance" });// => "54.4 gazillion-distance"i18n.numberToHuman(343, { units: "distance", precision: 1 });// => "300 meters"i18n.numberToHuman(1, { units: "distance" });// => "1 meter"i18n.numberToHuman(0.34, { units: "distance" });// => "34 centimeters"
method numberToHumanSize
numberToHumanSize: ( input: Numeric, options?: Partial<NumberToHumanSizeOptions>) => string;
Convert a number into a readable size representation.
Parameter input
The number that will be formatted.
Parameter options
The formatting options. When defined, supersedes the default options stored at
number.human.storage_units.*
andnumber.human.format
.Parameter
{number} options.precision Sets the precision of the number (defaults to 3).
Parameter
{RoundingMode} options.roundMode Determine how rounding is performed (defaults to
default
)Parameter
{boolean} options.significant If
true
, precision will be the number of significant digits. Iffalse
, the number of fractional digits (defaults totrue
).Parameter
{string} options.separator Sets the separator between the fractional and integer digits (defaults to ".").
Parameter
{string} options.delimiter Sets the thousands delimiter (defaults to "").
Parameter
{boolean} options.stripInsignificantZeros If
true
removes insignificant zeros after the decimal separator (defaults totrue
).Returns
{string} The formatted number.
Example 1
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"
method numberToPercentage
numberToPercentage: ( input: Numeric, options?: Partial<NumberToPercentageOptions>) => string;
Convert a number into a formatted percentage value.
Parameter input
The number to be formatted.
Parameter options
The formatting options. When defined, supersedes the default options stored at
number.format
andnumber.percentage.*
.Parameter
{number} options.precision Sets the level of precision (defaults to 3).
Parameter
{RoundingMode} options.roundMode Determine how rounding is performed (defaults to
default
.)Parameter
{string} options.separator Sets the separator between the units (defaults to ".").
Parameter
{string} options.delimiter Sets the thousands delimiter (defaults to "").
Parameter
{string} options.format Sets the format for non-negative numbers (defaults to "%n%"). The number field is represented by
%n
.Parameter
{string} options.negativeFormat Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by
format
). Accepts the same fields thanformat
, except%n
is here the absolute value of the number.Parameter
{boolean} options.stripInsignificantZeros If
true
removes insignificant zeros after the decimal separator (defaults tofalse
).Returns
{string} The formatted number.
Example 1
i18n.numberToPercentage(100);// => "100.000%"i18n.numberToPercentage("98");// => "98.000%"i18n.numberToPercentage(100, { precision: 0 });// => "100%"i18n.numberToPercentage(1000, { delimiter: ".", separator: "," });// => "1.000,000%"i18n.numberToPercentage(302.24398923423, { precision: 5 });// => "302.24399%"i18n.numberToPercentage(1000, { precision: null });// => "1000%"i18n.numberToPercentage("98a");// => "98a%"i18n.numberToPercentage(100, { format: "%n %" });// => "100.000 %"i18n.numberToPercentage(302.24398923423, { precision: 5, roundMode: "down" });// => "302.24398%"
method numberToRounded
numberToRounded: ( input: Numeric, options?: Partial<NumberToRoundedOptions>) => string;
Convert number to a formatted rounded value.
Parameter input
The number to be formatted.
Parameter options
The formatting options.
Parameter
{number} options.precision Sets the precision of the number (defaults to 3).
Parameter
{string} options.separator Sets the separator between the fractional and integer digits (defaults to ".").
Parameter
{RoundingMode} options.roundMode Determine how rounding is performed.
Parameter
{boolean} options.significant If
true
, precision will be the number of significant_digits. Iffalse
, the number of fractional digits (defaults tofalse
).Parameter
{boolean} options.stripInsignificantZeros If
true
removes insignificant zeros after the decimal separator (defaults tofalse
).Returns
{string} The formatted number.
Example 1
i18n.numberToRounded(111.2345);// => "111.235"i18n.numberToRounded(111.2345, { precision: 2 });// => "111.23"i18n.numberToRounded(13, { precision: 5 });// => "13.00000"i18n.numberToRounded(389.32314, { precision: 0 });// => "389"i18n.numberToRounded(111.2345, { significant: true });// => "111"i18n.numberToRounded(111.2345, { precision: 1, significant: true });// => "100"i18n.numberToRounded(13, { precision: 5, significant: true });// => "13.000"i18n.numberToRounded(13, { precision: null });// => "13"i18n.numberToRounded(389.32314, { precision: 0, roundMode: "up" });// => "390"i18n.numberToRounded(13, {precision: 5,significant: true,stripInsignificantZeros: true,});// => "13"i18n.numberToRounded(389.32314, { precision: 4, significant: true });// => "389.3"i18n.numberToRounded(1111.2345, {precision: 2,separator: ",",delimiter: ".",});// => "1.111,23"
method onChange
onChange: (callback: OnChangeHandler) => () => void;
Add a callback that will be executed whenever locale/defaultLocale changes, or
I18n#store
/I18n#update
is called.Parameter callback
The callback that will be executed.
Returns
{Function} Return a function that can be used to unsubscribe the event handler.
method pluralize
pluralize: (count: number, scope: Scope, options?: TranslateOptions) => string;
Pluralize the given scope using the
count
value. The pluralized translation may have other placeholders, which will be retrieved fromoptions
.Parameter count
The counting number.
Parameter scope
The translation scope.
Parameter options
The translation options.
Returns
{string} The translated string.
method store
store: (translations: Dict) => void;
Update translations by merging them. Newest translations will override existing ones.
Parameter translations
An object containing the translations that will be merged into existing translations.
Returns
{void}
method strftime
strftime: ( date: Date, format: string, options?: Partial<StrftimeOptions>) => string;
Formats time according to the directives in the given format string. The directives begins with a percent (
%
) character. Any text not listed as a directive will be passed through to the output string.Parameter date
The date that will be formatted.
Parameter format
The formatting string.
Parameter options
The formatting options.
Returns
{string} The formatted date.
See Also
strftime
method timeAgoInWords
timeAgoInWords: ( fromTime: DateTime, toTime: DateTime, options?: TimeAgoInWordsOptions) => string;
Reports the approximate distance in time between two time representations.
Parameter fromTime
The initial time.
Parameter toTime
The ending time. Defaults to
Date.now()
.Parameter options
The options.
Parameter
{boolean} options.includeSeconds Pass
{includeSeconds: true}
if you want more detailed approximations when distance < 1 min, 29 secs.Parameter
{Scope} options.scope With the scope option, you can define a custom scope to look up the translation.
Returns
{string} The distance in time representation.
method toSentence
toSentence: (items: any[], options?: Partial<ToSentenceOptions>) => string;
Converts the array to a comma-separated sentence where the last element is joined by the connector word.
Parameter items
The list of items that will be joined.
Parameter options
The options.
Parameter
{string} options.wordsConnector The sign or word used to join the elements in arrays with two or more elements (default: ", ").
Parameter
{string} options.twoWordsConnector The sign or word used to join the elements in arrays with two elements (default: " and ").
Parameter
{string} options.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 1
i18n.toSentence(["apple", "banana", "pineapple"]);//=> apple, banana, and pineapple.
method toTime
toTime: (scope: Scope, input: DateTime) => string;
Convert the given dateString into a formatted date.
Parameter scope
The formatting scope.
Parameter input
The string that must be parsed into a Date object.
Returns
{string} The formatted date.
method translate
translate: <T = string>(scope: Scope, options?: TranslateOptions) => string | T;
Translate the given scope with the provided options.
Parameter scope
The scope that will be used.
Parameter options
The options that will be used on the translation. Can include some special options like
defaultValue
,count
, andscope
. Everything else will be treated as replacement values.Parameter
{number} options.count Enable pluralization. The returned translation will depend on the detected pluralizer.
Parameter
{any} options.defaultValue The default value that will used in case the translation defined by
scope
cannot be found. Can be a function that returns a string; the signature is(i18n:I18n, options: TranslateOptions): string
.Parameter
{MissingBehavior|string} options.missingBehavior The missing behavior that will be used instead of the default one.
Parameter
{Dict[]} options.defaults An array of hashs where the key is the type of translation desired, a
scope
or amessage
. The translation returned will be either the first scope recognized, or the first message defined.Returns
{T | string} The translated string.
method update
update: (path: string, override: any, options?: { strict: boolean }) => void;
You may want to update a part of your translations. This is a public interface for doing it so.
If the provided path exists, it'll be replaced. Otherwise, a new node will be created. When running in strict mode, paths that doesn't already exist will raise an exception.
Strict mode will also raise an exception if the override type differs from previous node type.
Parameter path
The path that's going to be updated. It must include the language, as in
en.messages
.Parameter override
The new translation node.
Parameter options
Set options.
Parameter
{boolean} options.strict Raise an exception if path doesn't already exist, or if previous node's type differs from new node's type.
Returns
{void}
Example 1
i18n.update("en.number.format", {unit: "%n %u"});i18n.update("en.number.format", {unit: "%n %u"}, true);
method withLocale
withLocale: (locale: string, callback: () => void) => Promise<void>;
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.Parameter locale
The temporary locale that will be set during the function's execution.
Parameter callback
The function that will be executed with a temporary locale set.
Returns
{void}
Example 1
await i18n.withLocale("pt", () => {console.log(i18n.t("hello"));});
class Locales
class Locales {}
constructor
constructor(i18n: I18n);
method get
get: (locale: string) => string[];
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.
i18n.locales.get("de-DE");// ["de-DE", "de", "en"]Parameter locale
The locale query.
Returns
{string[]} The list of locales.
method register
register: ( locale: string, localeResolver: LocaleResolver | string | string[]) => void;
You can define custom rules for any locale. Just make sure you return an array containing all locales.
// Default the Wookie locale to English.i18n.locales.register("wk", (_i18n, locale) => {return ["en"];});Parameter locale
The locale's name.
Parameter localeResolver
The locale resolver strategy.
Returns
{void}
class MissingTranslation
class MissingTranslation {}
constructor
constructor(i18n: I18n);
method get
get: (scope: Scope, options: Dict) => string;
Return a missing translation message for the given parameters.
Parameter scope
The translations' scope.
Parameter options
The translations' options.
Returns
{string} The missing translation.
method register
register: (name: string, strategy: MissingTranslationStrategy) => void;
Registers a new missing translation strategy. This is how messages are defined when a translation cannot be found.
The follow example registers a strategy that always return the phrase "Oops! Missing translation.".
Parameter name
The strategy name.
Parameter strategy
A function that returns a string the result of a missing translation scope.
Returns
{void}
Example 1
i18n.missingTranslation.register("oops",(i18n, scope, options) => "Oops! Missing translation.");i18n.missingBehavior = "oops";
class Pluralization
class Pluralization {}
This class enables registering different strategies for pluralization, as well as getting a pluralized translation.
The default pluralization strategy is based on three counters:
-
one
: returned when count is equal to absolute1
. -zero
: returned when count is equal to0
. If this translation is not set, then it defaults toother
. -other
: returned when count is different than absolute1
.When calling
i18n.translate
(or its alias), pluralization rules will be triggered whenever the translation options containcount
.Example 1
A JSON describing the pluralization rules.
{"en": {"inbox": {"zero": "You have no messages","one": "You have one message","other": "You have %{count} messages"}}}Example 2
How to get pluralized translations.
i18n.t("inbox", {count: 0}); // returns "You have no messages"i18n.t("inbox", {count: 1}); // returns "You have on message"i18n.t("inbox", {count: 2}); // returns "You have 2 messages"
constructor
constructor(i18n: I18n);
method get
get: (locale: string) => Pluralizer;
Returns a list of possible pluralization keys. This is defined by a chain of pluralizers, going from locale set explicitly, then the locale set through
i18n.locale
, defaulting todefaultPluralizer
.Parameter locale
The locale.
Returns
{Pluralizer} The pluralizer function.
method register
register: (locale: string, pluralizer: Pluralizer) => void;
Register a new pluralizer strategy.
You may want to support different pluralization rules based on the locales you have to support. If you do, make sure you submit a pull request at <https://github.com/fnando/i18n> so we can distribute it. For now only Russian is distributed.
The pluralizer will receive the
I18n
instance, together withcount
. Is up to the pluralizer to return a list of possible keys given that count. The Russian pluralizer, for instance, returnsone
,few
,many
,other
as possible pluralization keys.You can view a complete list of pluralization rules at [unicode.org](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html).
You can also leverage [make-plural](https://github.com/eemeli/make-plural/), rather than writing all your pluralization functions. For this, you must wrap make-plural's function by using
useMakePlural({ pluralizer, includeZero, ordinal })
:Parameter locale
The locale.
Parameter pluralizer
The pluralizer function.
Returns
{void}
Example 1
import { ru } from "make-plural";import { useMakePlural } from "i18n-js";i18n.pluralization.register("ru", useMakePlural({ pluralizer: ru }));
Interfaces
interface Dict
interface Dict {}
index signature
[key: string]: any;
interface FormatNumberOptions
interface FormatNumberOptions {}
property delimiter
delimiter: string;
property format
format: string;
property negativeFormat
negativeFormat: string;
property precision
precision: number | null;
property raise
raise: boolean;
property roundMode
roundMode: RoundingMode;
property separator
separator: string;
property significant
significant: boolean;
property stripInsignificantZeros
stripInsignificantZeros: boolean;
property unit
unit: string;
interface I18nOptions
interface I18nOptions {}
property defaultLocale
defaultLocale: string;
Set default locale. This locale will be used when fallback is enabled and the translation doesn't exist in a particular locale. Defaults to
en
.{string}
property defaultSeparator
defaultSeparator: string;
Set the default string separator. Defaults to
.
, as inscope.translation
.{string}
property enableFallback
enableFallback: boolean;
Set if engine should fallback to the default locale when a translation is missing. Defaults to
false
.When enabled, missing translations will first be looked for in less specific versions of the requested locale and if that fails by taking them from your
I18n#defaultLocale
.{boolean}
property locale
locale: string;
Set the current locale. Defaults to
en
.{string}
property missingBehavior
missingBehavior: MissingBehavior;
Set missing translation behavior.
-
message
will display a message that the translation is missing. -guess
will try to guess the string. -error
will raise an exception whenever a translation is not defined.See MissingTranslation.register for instructions on how to define your own behavior.
{MissingBehavior}
property missingPlaceholder
missingPlaceholder: MissingPlaceholderHandler;
Return a missing placeholder message for given parameters.
{MissingPlaceholderHandler}
property missingTranslationPrefix
missingTranslationPrefix: string;
If you use missingBehavior with 'message', but want to know that the string is actually missing for testing purposes, you can prefix the guessed string by setting the value here. By default, no prefix is used.
{string}
property nullPlaceholder
nullPlaceholder: NullPlaceholderHandler;
Return a placeholder message for null values. Defaults to the same behavior as
I18n.missingPlaceholder
.{NullPlaceholderHandler}
property placeholder
placeholder: RegExp;
Set the placeholder format. Accepts
{{placeholder}}
and%{placeholder}
.{RegExp}
property transformKey
transformKey: (key: string) => string;
Transform keys. By default, it returns the key as it is, but allows for overriding. For instance, you can set a function to receive the camelcase key, and convert it to snake case.
{function}
interface ObjectType
interface ObjectType {}
index signature
[key: string]: PrimitiveType | ArrayType | ObjectType;
interface StrftimeOptions
interface StrftimeOptions {}
property abbrDayNames
abbrDayNames: DayNames;
property abbrMonthNames
abbrMonthNames: MonthNames;
property dayNames
dayNames: DayNames;
property meridian
meridian: { am: string; pm: string;};
property monthNames
monthNames: MonthNames;
property utc
utc?: boolean;
interface TimeAgoInWordsOptions
interface TimeAgoInWordsOptions {}
property includeSeconds
includeSeconds?: boolean;
property scope
scope?: Scope;
interface ToSentenceOptions
interface ToSentenceOptions {}
property lastWordConnector
lastWordConnector: string;
property twoWordsConnector
twoWordsConnector: string;
property wordsConnector
wordsConnector: string;
interface TranslateOptions
interface TranslateOptions {}
property count
count?: number;
property defaults
defaults?: Dict[];
property defaultValue
defaultValue?: any;
property missingBehavior
missingBehavior?: MissingBehavior | string;
property scope
scope?: Scope;
index signature
[key: string]: any;
Type Aliases
type AnyObject
type AnyObject = PrimitiveType | ArrayType | ObjectType;
type ArrayType
type ArrayType = AnyObject[];
type DateTime
type DateTime = string | number | Date;
type DayNames
type DayNames = [string, string, string, string, string, string, string];
type LocaleResolver
type LocaleResolver = (i18n: I18n, locale: string) => string[];
type MakePlural
type MakePlural = (count: number, ordinal?: boolean) => string;
type MissingBehavior
type MissingBehavior = 'message' | 'guess' | 'error';
Possible missing translation behavior. {String}
type MissingPlaceholderHandler
type MissingPlaceholderHandler = ( i18n: I18n, placeholder: string, message: string, options: Dict) => string;
type MissingTranslationStrategy
type MissingTranslationStrategy = ( i18n: I18n, scope: Scope, options: Dict) => string;
type MonthNames
type MonthNames = [ null, string, string, string, string, string, string, string, string, string, string, string, string];
type NullPlaceholderHandler
type NullPlaceholderHandler = ( i18n: I18n, placeholder: string, message: string, options: Dict) => string;
type NumberToCurrencyOptions
type NumberToCurrencyOptions = FormatNumberOptions;
type NumberToDelimitedOptions
type NumberToDelimitedOptions = { delimiterPattern: RegExp; delimiter: string; separator: string;};
type NumberToHumanOptions
type NumberToHumanOptions = Omit< FormatNumberOptions, 'negativeFormat' | 'unit' | 'raise'> & { units: NumberToHumanUnits | string;};
type NumberToHumanSizeOptions
type NumberToHumanSizeOptions = Omit< FormatNumberOptions, 'format' | 'negativeFormat' | 'raise'>;
type NumberToHumanUnits
type NumberToHumanUnits = { [key: string]: string;};
type NumberToPercentageOptions
type NumberToPercentageOptions = Omit<FormatNumberOptions, 'raise'>;
type NumberToRoundedOptions
type NumberToRoundedOptions = Omit< FormatNumberOptions, 'format' | 'negativeFormat' | 'raise'> & { precision: number };
type Numeric
type Numeric = BigNumber | string | number;
type OnChangeHandler
type OnChangeHandler = (i18n: I18n) => void;
type Pluralizer
type Pluralizer = (i18n: I18n, count: number) => string[];
type PrimitiveType
type PrimitiveType = number | string | null | undefined | boolean;
type RoundingMode
type RoundingMode = | 'up' | 'down' | 'truncate' | 'halfUp' | 'default' | 'halfDown' | 'halfEven' | 'banker' | 'ceiling' | 'ceil' | 'floor';
Controls handling of arithmetic exceptions and rounding.
- "up": round away from zero - "down" or "truncate": round towards zero (truncate) - "halfUp" or "default": round towards the nearest neighbor, unless both neighbors are equidistant, in which case round away from zero. - "halfDown": round towards the nearest neighbor, unless both neighbors are equidistant, in which case round towards zero. - "halfEven" or "banker": round towards the nearest neighbor, unless both neighbors are equidistant, in which case round towards the even neighbor (Banker’s rounding) - "ceiling" or "ceil": round towards positive infinity - "floor": round towards negative infinity
{string}
type Scope
type Scope = Readonly<string | string[]>;
Package Files (6)
Dependencies (3)
Dev Dependencies (21)
- @fnando/codestyle
- @fnando/eslint-config-codestyle
- @types/jest
- @types/lodash
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- esbuild
- eslint
- eslint-config-prettier
- eslint-plugin-import
- eslint-plugin-jest
- eslint-plugin-prettier
- jest
- jest-filename-transform
- jest-hud-reporter
- prettier
- ts-jest
- typedoc
- typescript
- webpack
- webpack-cli
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/i18n-js
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/i18n-js)
- HTML<a href="https://www.jsdocs.io/package/i18n-js"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6021 ms. - Missing or incorrect documentation? Open an issue for this package.