easy-intl v0.0.2
Easy Intl 🌎
Utility for easy use of the Internationalization API
Table of Contents
Installation
yarn add easy-intl
# or
npm i easy-intlUsage
<main data-intl_root id="global_root">
<h1
data-intl_type="custom"
data-intl_value="main_title"
data-intl_map="main_title"
>
easy Intl
</h1>
<section class="card">
<img
src="https://cdn-icons-png.flaticon.com/512/814/814513.png"
alt=""
role="presentation"
/>
<select id="locale">
<option value="ru-RU">Ru</option>
<option value="en-US" selected>En</option>
<option value="de-DE">De</option>
<option value="ja-JP">Ja</option>
</select>
</section>
<div class="container">
<section class="card">
<h2
data-intl_type="custom"
data-intl_value="date_title"
data-intl_map="date_title"
>
Дата и время
</h2>
<div class="box">
<h3 data-intl_type="custom" data-intl_value="without_options">
Без встроенных настроек
</h3>
<time data-intl_type="date" data-intl_value="2021-08-16 12:00">
16.08.2021 12:00
</time>
</div>
<div class="box">
<h3 data-intl_type="custom" data-intl_value="with_options">
Со встроенными настройками
</h3>
<time
data-intl_type="date"
data-intl_value="2021-08-16 12:00"
data-intl_options="dateStyle: long, timeStyle: 'short'"
>
16 августа 2021 г., 12:00
</time>
</div>
</section>
<section data-intl_root id="local_root" class="card">
<h2 data-intl_type="custom" data-intl_value="date_title">
Дата и время
</h2>
<div class="box">
<h3 data-intl_type="custom" data-intl_value="without_options">
Без встроенных настроек
</h3>
<time data-intl_type="date" data-intl_value="2021-08-16 12:00">
16.08.2021 12:00
</time>
</div>
<div class="box">
<h3 data-intl_type="custom" data-intl_value="with_options">
Со встроенными настройками
</h3>
<time
data-intl_type="date"
data-intl_value="2021-08-16 12:00"
data-intl_options="day: 'numeric', month: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'"
>
16 августа 2021 г., 12:00
</time>
</div>
</section>
</div>
</main>import { EasyIntl } from 'easy-intl'
import options from './intl/options.js'
import dictionary from './intl/dictionary.js'
// global localization
const globalIntl = new EasyIntl({
locale: 'en-US',
root: '#global_root',
dictionary,
...options
})
console.log(globalIntl.elements)
console.log(globalIntl.map)
console.log(globalIntl.map['main_title'])
// local localization
const localIntl = new EasyIntl({
autorun: false,
dictionary,
date: { day: '2-digit', month: 'long', year: 'numeric' }
})
localIntl.locale = 'ja-JP'
localIntl.root = '#local_root'
// manual localization
localIntl.localize()
const localeSelector = document.querySelector('#locale')
localeSelector.onchange = (e) => {
// auto localization
globalIntl.locale = e.target.value
}// options
export default {
date: { dateStyle: 'short' },
relative: { numeric: 'auto' },
number: { style: 'decimal' },
names: { type: 'language' },
list: { type: 'conjunction' }
}// dictionary
export default {
'ru-RU': {
main_title: 'Пример использования Easy Intl',
without_options: 'Без встроенных настроек',
with_options: 'Со встроенными настройками',
locale_title: 'Локаль',
date_title: 'Дата и время',
relative_title: 'Относительное время',
number_title: 'Число',
currency_title: 'Валюта',
unit_title: 'Единицы измерения',
names_title: 'Названия языков и т.д.',
list_title: 'Список'
},
'en-US': {
main_title: 'Example of use Easy Intl',
without_options: 'Without inline options',
with_options: 'With inline options',
locale_title: 'Locale',
date_title: 'Date and time',
relative_title: 'Relative time',
number_title: 'Number',
currency_title: 'Currency',
unit_title: 'Units',
names_title: 'Language names etc.',
list_title: 'List'
}
}By default EasyIntl localize textContent property, title and placeholder attribute values of HTML elements with data-intl_type attribute. Use intl.map object if you need to localize other things (don't forget to add data-intl_map attribute to corresponding elements).
HTML attributes
data-intl_root- indicator for root HTML element (when global and local (or multiple local) localizations used)data-intl_type-date|relative|number|names|list|compare|plural|customdata-intl_value- for
date- any validdate|time|datetime - for
relative-stringwithamountandunit, e.g.1 day|-1_week(separators: space | underscore) - for
number-number|string - for
names- language | country code - for
list-array|string, e.g['Chrome', 'Firefox', 'Safari']|Chrome, Firefox, Safari.stringmay include square brackets[], single, double or back quotes'", e.g.Chrome, 'Firefox'; "Safari"(separators: comma | semicolon) - for
compare-array|string(⬆) - for
plural-number - for
custom-string: key from dictionary
- for
data-intl_options- any valid options for corresponding util (depends ondata-intl_type; ⬇)data-intl_map-string: key forintl.map: { [data-intl_map]: localized data-intl_value }
Signature of EasyIntl class
const intl = new EasyIntl(options)Options
locale: string- language | country coderoot: HTMLElement | string-HTMLElement| any validCSS-selectorautorun: boolean- iftrue, localization will be execute on everylocaleproperty updatedictionary: { [key: string]: string }- dictionary for custom localizationdate: { [key: string]: string }- options fordatemethod (formatDateTimeutil)relative: { [key: string]: string }- options forrelativemethod (formatRelativeTimeutil)number: { [key: string]: string }- options fornumbermethod (formatNumberutil)names: { [key: string]: string }- options fornamesmethod (formatNamesutil)list: { [key: string]: string }- options forlistmethod (formatListutil)compare: { [key: string]: string }- options forcomparemethod (compareValuesutil)plural: { [key: string]: string }- options forpluralmethod (pluralizeutil)
Default options
{
locale: [],
root: document.body,
autorun: true,
options: {},
dictionary: {},
elements: [],
map: {}
}Props (getters/setters)
intl.locale: stringintl.root: HTMLElement | stringintl.autorun: booleanintl.dictionary: { [key: string]: string }intl.elements: HTMLElement[]- HTML elements withdata-intl_typeattribute -readonlyintl.map: { [key: string]: string }-keyis the value ofdata-intl_mapattribute,valueis the localized value ofdata-intl_valueattribute -readonlyintl.options: { [key: string]: { [key: string]: string } }= options for corresponding methods
Setting locale property results in auto localization when autorun: true.
Methods
intl.date(date: Date, options)
intl.relative(value: string, options)
intl.number(number: number, options)
intl.names(localeOf: string, options)
intl.list(list: array | string, options)
intl.compare(values: array | string, options)
intl.plural(number: number, options)
intl.custom(value: string) // dictionary must be provided
intl.localize(options) // locale, root, date, relative etc.Utils signatures
Common options for all utils
localeMatcher-lookup|best fitformatMatcher-basic|best fit
formatDateTime
Util for Intl.DateTimeFormat
Signature
formatDateTime(options) // intl.date(date, options)Options
locale- language | country codedate- any validdate|time|datetimetimeZone-UTC,America/New_York,Europe/Parisetc.calendar-chinese,gregory,hebrew,indian,islamicetc.numberingSystem-arab,beng,fullwide,latinetc.hour12: boolean- iftrue, time will be present as12pm,4ametc.hourCycle-h11,h12,h23,h24etc.dateStyle-full|long|medium|shortweekday-long|short|narrowday-numeric|2-digitmonth-numeric|2-digit|long|short|narrowyear-numeric|2-digitera-long|short|narrowtimeStyle-full|long|medium|shorthour-numeric|2-digitminute-numeric|2-digitsecond-numeric|2-digitdayPeriod-narrow|short|longtimeZoneName-long|short
Default options
{
locale: [],
date: new Date(),
dateStyle: 'short'
}Example
import { formatDateTime } from 'easy-intl'
console.log(
'\n',
// my default locale is `ru-RU`
formatDateTime(), // 17.08.2021
'\n',
formatDateTime({ locale: 'en-US', dateStyle: 'short', timeStyle: 'short' }), // 8/17/21, 3:57 PM,
'\n',
formatDateTime({ locale: 'en-GB', dateStyle: 'long', timeStyle: 'short' }), // 17 August 2021 at 15:57
'\n',
formatDateTime({ locale: 'ja-JP', dateStyle: 'short' }), // 2021/08/17
'\n',
formatDateTime({ locale: 'es-ES', dateStyle: 'full', timeStyle: 'full' }), // martes, 17 de agosto de 2021, 15:57:49 (hora estándar de Ekaterimburgo)
'\n',
formatDateTime({
locale: 'fr-FR',
weekday: 'long',
day: '2-digit',
month: 'long',
year: 'numeric',
hour: '2-digit'
}) // mardi 17 août 2021, 15 h
)formatRelativeTime
Util for Intl.RelativeTimeFormat
Signature
formatRelativeTime(options) // intl.relative(value, options)Options
locale- language | country codevalue-stringwithamountandunit(may be separated by space or underscore), e.g.1 week,-2 day,3_monthetc.numeric-alwayse.g.1 day ago|autoe.g.yesterdaystyle-long|short|narrow
Default options
{
locale: [],
value: '1 day',
numeric: 'always'
}Example
import { formatRelativeTime } from 'easy-intl'
console.log(
'\n',
// default value is `1 day`
// my default locale is `ru-RU`
formatRelativeTime(), // через 1 день
'\n',
formatRelativeTime({ locale: 'en-US', value: '-1 day', numeric: 'auto' }), // yesterday
'\n',
formatRelativeTime({
locale: 'fr-FR',
value: '1_week',
style: 'long'
}), // dans 1 semaine
'\n',
formatRelativeTime({
locale: 'ja-JP',
value: '-1_month',
numeric: 'auto',
style: 'long'
}) // 先月
)formatNumber
Util for Intl.NumberFormat
Signature
formatNumber(options) // intl.number(number, options)Options
locale- language | country codenumberstyle-decimal|currency|percent|unit. Other options depends on this valuenotation-standard|scientific|engineering|compactnumberingSystem-arab,beng,deva,fullwide,latnetc.minimumIntegerDigits-1by defaultminimumFractionDigits-0by defaultmaximumFractionDigits- highest number ofminimumFractionDigitsand3minimumSignificantDigits-1by defaultmaximumSignificantDigits-minimumSignificantDigitsby defaultsignDisplay-auto|never|always|exceptZerouseGrouping: boolean- iffalse, thousands separators will be ignoredcompactDisplay- formatting style whennotation: compactcurrency-USD,EUR,RUBetc. (whenstyle: currency)currencyDisplay- displaying sign or name of currency whenstyle: currencycurrencySign:standard|accounting(whenstyle: currency)unit:centimeter,meter,minute,hour,byteetc.unitDisplay:long|short|narrow(whenstyle: unit)
Default options
{
locale: [],
number: 0,
style: 'decimal'
}Example
import { formatNumber } from 'easy-intl'
console.log(
'\n',
// my default locale is `ru-RU`
formatNumber({ number: 1234.56 }),
'\n', // 1 234,56
formatNumber({ locale: 'en-US', number: 1234.56 }),
'\n', // 1,234.56
formatNumber({ locale: 'de-DE', number: 1234.56, style: 'currency', currency: 'EUR' }),
'\n', // 1.234,56 €
formatNumber({ locale: 'fr-FR', number: 1234.56, style: 'percent' }),
'\n', // 123 456 %
formatNumber({
locale: 'it-IT',
number: 1234.56,
style: 'unit',
unit: 'celsius',
minimumFractionDigits: 3
}),
'\n' // 1.234,560 °C
)formatNames
Util for Intl.DisplayNames
Signature
formatNames(options) // intl.names(localeOf, options)Options
locale- language | country codelocaleOf- language | country codetype-language,region,script,currencystyle-long|short|narrowfallback-code|none
Default options
{
locale: [],
localeOf: 'en-US',
type: 'language'
}Example
import { formatNames } from 'easy-intl'
console.log(
'\n',
// my default locale is `ru-RU`
formatName(),
'\n', // американский английский
formatName({
localeOf: 'Egyp',
type: 'script'
}),
'\n', // египетская иероглифическая
formatName({
locale: 'fr-FR',
localeOf: 'AU',
type: 'region'
}),
'\n', // Australie
formatName({
locale: 'pl-PL',
localeOf: 'GBP',
type: 'currency',
style: 'long'
}),
'\n' // funt szterling
)formatList
Util for Intl.ListFormat
Signature
formatList(options) // intl.list(list, options)Options
locale- language | country codelist-array|stringtype-conjunction(and) |disjunction(or) |unitstyle-long|short|narrow
Default options
{
locale: [],
list: [],
type: 'conjunction'
}Example
import { formatList } from 'easy-intl'
const list = ['Chrome', 'Firefox', 'Safari']
console.log(
'\n',
// my default locale is `ru-RU`
formatList({ list }),
'\n', // Chrome, Firefox и Safari
formatList({ locale: 'en-US', list, style: 'short' }),
'\n', // Chrome, Firefox, & Safari
formatList({ locale: 'ja-JP', list, type: 'disjunction' }),
'\n' // Chrome、Firefox、またはSafari
)compareValues
Util for Intl.Collator
Signature
compareValues(options) // intl.compare(values, options)Options
locale- language | country codevalues-array|stringusage-sort|searchsensitivity-base|accent|case|variantcollation-big5han|dict|direct|ducetetc.numeric-booleanignorePunctuation-booleancaseFirst-upper|lower|false
Default options
{
locale: [],
values: [],
usage: 'sort'
}Example
import { compareValues } from 'easy-intl'
console.log(
'\n',
compareValues({ values: ['a', 'á'], sensitivity: 'base' }),
'\n', // 0 -> equal
compareValues({ values: ['2', '10'] }),
'\n', // 1 -> '2' > '10'
compareValues({ values: ['2', '10'], numeric: true }),
'\n' // -1 -> 2 < 10
)pluralize
Util for Intl.PluralRules
Currently only en-US locale is supported.
Signature
pluralize(options) // intl.plural(number, options)Options
locale- language | country codenumbertype-cardinal|ordinal
Default options
{
locale: [],
number: 0,
type: 'cardinal'
}Example
import { pluralize } from 'easy-intl'
console.log(
'\n',
pluralize(),
'\n', // one
// only `en-US` locale supported
pluralize({ locale: 'ru-RU', type: 'ordinal' }),
'\n' // other
)