1.0.1 • Published 2 years ago

@dev-vortex/i18n-icu v1.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Internationalization with ICU Library

This library aims to provide an agnostic and reliable mechanism to proivide and support internationaliizatiion with static and live translation file fetching through minimal or no setup.

Installation

yarn add @dev-vortex/i18n-icu

or

npm install @dev-vortex/i18n-icu

Configuration

TODO: explain all the config options and how to pass the config to library

Formatted

TODO: explain how to format a date, currency, number, etc...

Translate

Local files (static)

Load files (dynamic)

Quick Start

  1. Import the initialization method to have access to the api

    import type { init } from '@dev-vortex/i18n-icu'
  2. Prepare the options for the initialization with the locale validator (this can be the type guardian of your app defined locales)

    import type { I18nInitOptions } from '@dev-vortex/i18n-icu'

const Locale = { EN_US: 'en-US', SV_SE: 'sv-SE', HR_HR: 'hr-HR', AR_AR: 'ar-AR', } as const

type AppLocaleKeys = keyof typeof Locale type AppLocaleValues = typeof Localekeyof typeof Locale

const isValidLocale = (toVerify: unknown): toVerify is AppLocaleValues => { const toReturn = !!Object.keys(Locale).find( value => Localevalue as AppLocaleKeys === toVerify, ) return toReturn }

const initOptions: I18nInitOptions = { checkValidLocale: isValidLocale, }

3. Prepare the `i18n` and `i18n-icu` option objects.
  > For the `i18n` we can just use the same as `i18next` [here](https://www.i18next.com/overview/configuration-options)
```typescript
const i18nOptions: InitOptions = {
   debug: false,
   fallbackLng: false,
   lng: deviceLocale(),
   saveMissing: true,
   parseMissingKeyHandler: parseMissingKeyHandler,
   missingKeyHandler: missingKeyHandler,
   resources: {
       [Locale.EN_US]: {
           translation: require(`./translations/${Locale.EN_US}.json`),
       },
       ...
   },
}

const i18nIcuOptions: I18nIcuInitOptions = {
   errorHandler: errorHandler,
}
  1. Call the init method to get the api.
const api = init(initOptions, i18nOptions, i18nIcuOptions)

API

Setting the language

Once we got the API we can start by settiing the current language

api.setLanguage('se_SV') // Normalizes and set the language

Get the current language

const currentLanguuage = api.getLanguage()

Get normalized locale

const currentLanguuage = api.normalizeLocale('en_GB')

Get the text for the provided key

const text = api.translate('KEY.TO.TEXT')