1.1.2 • Published 5 months ago

i18next-wc v1.1.2

Weekly downloads
21
License
MIT
Repository
github
Last release
5 months ago

i18next-wc

Web-components for i18next.

Handles formatting of intl messages as well as formatting date and numbers.

Usable as vanillaJS web-components as well as with JSX (react...).

The following components are available

For inspiration of this project credits go to kwc-i18next 👏.

Demopages are at https://spurreiter.github.io/i18next-wc

Table of contents

Installation

Install both i18next and this package as dependencies

npm i i18next-wc i18next

Usage

With a CDN...

<intl-message label="key"></intl-message>
<intl-datetime></intl-datetime>

<script src="https://unpkg.com/i18next@19/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-wc"></script>
<script>
  i18next.init({...})
</script>

In your own bundled code...

import i18Next from 'i18next'
import 'i18next-wc'

window.i18next = i18next

i18next.init(...)
<intl-message label="key"></intl-message>
<intl-datetime></intl-datetime>

<script src="./bundle.js"></script>

intl-message

Formats messages with i18next.

<intl-message label="test:key">
A value

<intl-message label="title" value="Title">
My Title

<intl-message label="deep" value='{"key":"Hello","val":"World"}'>
Hello World!

<intl-message label="html" value="<span style='color: red'>dangerous</span>">
With HTML it might get <span style='color: red'>dangerous</span>

<intl-message label="html" dangerous value="<span style='color: red'>dangerous</span>">
With HTML it might get dangerous

<intl-message label="item" count="1">
One item

<intl-message label="item" count="10">
10 items

<script src="https://unpkg.com/i18next@19/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-wc/dist/intl-message.js"></script>
<script>
  i18next.init({ // initialize i18next
    lng: "en",
    fallbackLng: "en",
    resources: {
      en: {
        default: {
          title: "My {{value}}",   deep: "{{value.key}} {{value.val}}!",
          item: "One item",        item_plural: "{{count}} items",
          html: "With HTML it might get {{value}}"
        },
        test: {
          key: "A value"
        }
      }
    },
    defaultNS: "default",
    fallbackNS: "global"
  })
</script>

Examples

Attributes

attributetypedescription
labelstringi18next translation label
keystringdeprecated use label instead; i18next translation label
countnumbercount for plurals
contextstringi18next context
valuestring, json, objectuse value for for default inserts
lngstringchanges default language
nsstring, string[]changes default namespace
optionsjson, objecti18next options. See i18next-options
dangerousbooleandangerously insert unescaped content (XSS!)
hiddenbooleanhide translation from rendering

Note: Avoid using key attribute with keyed frameworks as this attribute is used for referencing Elements in DOM. Use label attribute instead.

intl-datetime

<intl-datetime>
05/04/2020

<intl-datetime time>
22:03:47

<intl-datetime weekday="long">
dimanche

<intl-datetime value="2020-03-12" lng="en-GB">
12/03/2020

<intl-datetime value="2020-03-12" lng="en-US">
3/12/2020

<intl-datetime options='{"weekday":"short","year":"numeric","month":"long","day":"numeric"}'>
dim. 5 avril 2020

<intl-datetime date weekday="long" month="long" lng="ja">
2020年4月5日日曜日

<intl-datetime date time hour12 timeZoneName="short">
05/04/2020 à 10:03:47 PM UTC+2

<intl-datetime date time hourCycle="h12" timeZoneName="long" timeZone="Asia/Tokyo">
06/04/2020 à 5:03:47 heure normale du Japon

<intl-datetime date time hour12 timeZoneName="long" timeZone="Asia/Foobar">
05/04/2020

<!-- intl-datetime works also without i18next -->
<script src="https://unpkg.com/i18next@19/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-wc/dist/intl-datetime.js"></script>

Example

See examples/datetime.html.

Attributes

attributetypedescription
lngstringchanges default language
valueDate, ISOStringif string than use iso format. E.g. local date 2020-12-31 12:00:00 or UTC date 2020-12-31T12:00:00Z. Use always new Date().toISOString() to be on the safe side. If undefined current timestamp is used.
optionsjson, objectjson formatted string of DateTimeFormatOptions
weekdaystring"narrow", "short", "long"
erastring"narrow", "short", "long"
yearstring"2-digit", "numeric"
monthstring"2-digit", "numeric", "narrow", "short", "long"
daystring"2-digit", "numeric"
hourstring"2-digit", "numeric"
minutesstring"2-digit", "numeric"
secondsstring"2-digit", "numeric"
hour12booleanuse AM, PM if true
hourCyclestring"h11", "h12", "h23", "h24"
timeZonestringtimezone of date e.g. "Asia/Tokyo"
timeZoneNamestring"short", "long"
localeMatcherstring"lookup", "best fit"
formatMatcherstring"basic", "best fit"
numberingSystemstring"arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt"
calendarstringbuddhist", "chinese", "coptic", "ethiopia", "ethiopic", "gregory", "hebrew", "indian", "islamic", "iso8601", "japanese", "persian", "roc"
datebooleanif set display date
timebooleanif set display time

intl-relative-time

⚠ NOTE: Consider using a polyfill for Safari, Safari iOS and Edge

Example

See examples/relative-time.html.

Attributes

attributetypedescription
lngstringchanges default language
valueDate, ISOStringif string than use iso format. E.g. local date 2020-12-31 12:00:00 or UTC date 2020-12-31T12:00:00Z. Use always new Date().toISOString() to be on the safe side
optionsjson, objectjson formatted string of todo
unitstring"year", "quarter", "month", "week", "day", "hour", "minute", "second"
stylestring"narrow", "short", "long"
numericstring"always", "auto"
localeMatcherstring"lookup", "best fit"
updatebooleanautomatically update value

intl-number

<intl-number value="123456.789">
123.456,789

<intl-number value="123456.789" lng="en-IN">
1,23,456.789

<intl-number value="123456.789" lng="ar-EG">
١٢٣٬٤٥٦٫٧٨٩

<intl-number value="123456.789" lng="zh-Hans-CN-u-nu-hanidec">
一二三,四五六.七八九

<intl-number value="123456.789" lng="de-DE" options='{"style":"currency","currency":"EUR"}'>
123.456,79 €

<intl-number value="123456.789" lng="ja-JP" p-style="currency" currency="JPY">
¥123,457

<intl-number value="123456.789" lng="en-IN" maximumSignificantDigits="3">
1,23,000

<intl-number value="50" lng="pt-PT" p-style="unit" unit="mile-per-hour">
50 mi/h

<intl-number value="12" lng="en-GB" p-style="unit" unit="liter" unitDisplay="long">
12 litres

<intl-number value="987654321" lng="en-US" notation="scientific">
9.877E8

<intl-number value="987654321" lng="pt-PT" notation="scientific">
9,877E8

<intl-number value="987654321" lng="en-GB" notation="engineering">
987.654E6

<intl-number value="987654321" lng="de" notation="engineering">
987,654E6

<intl-number value="987654321" lng="zh-CN" notation="compact">
9.9亿

<intl-number value="987654321" lng="fr" notation="compact">
988 M

<!-- intl-number works also without i18next -->
<script src="https://unpkg.com/i18next@19/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-wc/dist/intl-number.js"></script>

Example

See examples/number.html.

Attributes

attributetypedescription
lngstringchanges default language
valuenumbervalue as number string
optionsjson or objectobject or json formatted string of NumberFormatOptions
stylePropstring"decimal", "percent", "currency", "unit" alternatively use style within options
currencystringISO 4217 currency and funds code e.g. "EUR", "USD"
currencyDisplaystring"code", "symbol", "narrowSymbol", "name"
currencySignstring"standard", "accounting"
unitstringSee TC39 IsSanctionedSimpleUnitIdentifier
unitDisplaystring"short", "narrow", "long"
notationstring"standard", "scientific", "engineering", "compact"
compactDisplaystring"short", "long"
useGroupingboolean
signDisplaystring"auto", "never", "always", "exceptZero"
localeMatcherstring"lookup", "best fit"
minimumIntegerDigitsnumber1...21
minimumFractionDigitsnumber1...21
maximumFractionDigitsnumber1...21
minimumSignificantDigitsnumber1...21
maximumSignificantDigitsnumber1...21
numberingSystemstring"arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt"

Using with JSX

You can use all components in JSX (react, apprun, ...) as well.

Check examples/jsx.html

import i18next from "i18next"

// take care of treeshaking - removing the below line may cause that the Wc gets removed by treeshaking
import 'i18next-wc'
import { intlMessage } from 'i18next-wc'

// initialize i18next
i18next.init({
  lng: 'en-GB',
  fallbackLng: "en",
  resources: {
    en: {
      default: {
        placeholder: 'fill in here',
        'Selected language': 'Selected language: {{value}}'
      },
    },
    fr: {
      default: {
        placeholder: 'remplir ici',
        'Selected language': 'Langue choisie : {{value}}'
      }
    }
  },
  defaultNS: 'default'
})

// inject i18next into web-component
const IntlMessage = (props) => (<intl-message { ...{i18next, ...props }} />)

// use in your custom component
export function JsxComponent ({ lng }) {
  return (
    <>
      <IntlMessage label="Selected language" value={lng} />
      <input placeholder={intlMessage({i18next, label: 'placeholder'})} />
    </>
  )
}

Contributing

Feel free to clone the project and submit a PR. On contributing you implicitly agree to license your code under the terms of the MIT license.

License

MIT Licensed

References