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-intl
Usage
<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
|custom
data-intl_value
- for
date
- any validdate
|time
|datetime
- for
relative
-string
withamount
andunit
, 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
.string
may 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-selector
autorun: boolean
- iftrue
, localization will be execute on everylocale
property updatedictionary: { [key: string]: string }
- dictionary for custom localizationdate: { [key: string]: string }
- options fordate
method (formatDateTime
util)relative: { [key: string]: string }
- options forrelative
method (formatRelativeTime
util)number: { [key: string]: string }
- options fornumber
method (formatNumber
util)names: { [key: string]: string }
- options fornames
method (formatNames
util)list: { [key: string]: string }
- options forlist
method (formatList
util)compare: { [key: string]: string }
- options forcompare
method (compareValues
util)plural: { [key: string]: string }
- options forplural
method (pluralize
util)
Default options
{
locale: [],
root: document.body,
autorun: true,
options: {},
dictionary: {},
elements: [],
map: {}
}
Props (getters/setters)
intl.locale: string
intl.root: HTMLElement | string
intl.autorun: boolean
intl.dictionary: { [key: string]: string }
intl.elements: HTMLElement[]
- HTML elements withdata-intl_type
attribute -readonly
intl.map: { [key: string]: string }
-key
is the value ofdata-intl_map
attribute,value
is the localized value ofdata-intl_value
attribute -readonly
intl.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 fit
formatMatcher
-basic
|best fit
formatDateTime
Util for Intl.DateTimeFormat
Signature
formatDateTime(options) // intl.date(date, options)
Options
locale
- language | country codedate
- any validdate
|time
|datetime
timeZone
-UTC
,America/New_York
,Europe/Paris
etc.calendar
-chinese
,gregory
,hebrew
,indian
,islamic
etc.numberingSystem
-arab
,beng
,fullwide
,latin
etc.hour12: boolean
- iftrue
, time will be present as12pm
,4am
etc.hourCycle
-h11
,h12
,h23
,h24
etc.dateStyle
-full
|long
|medium
|short
weekday
-long
|short
|narrow
day
-numeric
|2-digit
month
-numeric
|2-digit
|long
|short
|narrow
year
-numeric
|2-digit
era
-long
|short
|narrow
timeStyle
-full
|long
|medium
|short
hour
-numeric
|2-digit
minute
-numeric
|2-digit
second
-numeric
|2-digit
dayPeriod
-narrow
|short
|long
timeZoneName
-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
-string
withamount
andunit
(may be separated by space or underscore), e.g.1 week
,-2 day
,3_month
etc.numeric
-always
e.g.1 day ago
|auto
e.g.yesterday
style
-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 codenumber
style
-decimal
|currency
|percent
|unit
. Other options depends on this valuenotation
-standard
|scientific
|engineering
|compact
numberingSystem
-arab
,beng
,deva
,fullwide
,latn
etc.minimumIntegerDigits
-1
by defaultminimumFractionDigits
-0
by defaultmaximumFractionDigits
- highest number ofminimumFractionDigits
and3
minimumSignificantDigits
-1
by defaultmaximumSignificantDigits
-minimumSignificantDigits
by defaultsignDisplay
-auto
|never
|always
|exceptZero
useGrouping: boolean
- iffalse
, thousands separators will be ignoredcompactDisplay
- formatting style whennotation: compact
currency
-USD
,EUR
,RUB
etc. (whenstyle: currency
)currencyDisplay
- displaying sign or name of currency whenstyle: currency
currencySign
:standard
|accounting
(whenstyle: currency
)unit
:centimeter
,meter
,minute
,hour
,byte
etc.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
,currency
style
-long
|short
|narrow
fallback
-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
|string
type
-conjunction
(and) |disjunction
(or) |unit
style
-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
|string
usage
-sort
|search
sensitivity
-base
|accent
|case
|variant
collation
-big5han
|dict
|direct
|ducet
etc.numeric
-boolean
ignorePunctuation
-boolean
caseFirst
-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 codenumber
type
-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
)