0.1.2 • Published 6 years ago

meri-i18n v0.1.2

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

meri-i18n

Internationalization (i18n) library in JS supporting genitives.

SETUP

Install dependencies

npm install meri-i18n
yarn add meri-i18n

Usage

A files tree looks like this:

src
├── i18n
|   ├── en_US.js
|   ├── fr_FR.js
|   └── index.js # exports all language packs
├── services
|   └── i18n.js # configuration file
└── index.js # root file

Define src/i18n/en_US.js file with translations:

const lang = {
  name: 'English',
  shortcut: 'en',
  fallbackLang: null,
  translations: {
    'sample.key': 'Awesome!',
    'sample.key.with.props': 'My car is {color}',
    'sample.key.genitive': {
      phrase: 'You have {unreadCount} {genitive:unreadCount}',
      genitives: {
        unreadCount: {
          '1:1': 'message',
          others: 'messages',
        }
      }
    },
  },
}

export default lang

fallbackLang - e.g. for fr_BE may be "fr_FR"

Define src/i18n/index.js exports file:

import en_US from './en_US'
import fr_FR from './fr_FR'

const languagePacks = {
  en_US,
  fr_FR,
}

export default languagePacks

Define src/services/i18n.js root file:

import I18n from 'meri-i18n'
import languagePacks from './i18n'

const i18n = new I18n({
  cookieName: 'locale',
  defaultLocale: 'en_US',
  debug: process.env.NODE_ENV === 'development',
  handleChange: (locale, cookieName, cookies) => {
    cookies.set(cookieName, locale)
    // reload page?
  },
  languagePacks,
})

export default i18n

Root file:

import i18n from './services/i18n'

// output: Awesome!
console.log(i18n.trans('sample.key'))

// output: My car is blue
console.log(i18n.trans('sample.key.with.props', { color: 'blue' }))

// output: You have 1 message
console.log(i18n.trans('sample.key.genitive', { unreadCount: 1 }))

// output: You have 99 messages
console.log(i18n.trans('sample.key.genitive', { unreadCount: 99 }))

// change
i18n.change('fr_FR')

// Current lang
console.log(i18n.current)

// All defined languages
console.log(i18n.list)

React - Redux

Example:

import store from './your-configuration-store-path'
import i18n from './your-configuration-i18n-path'

const i18n.handleChange = (locale, cookieName, cookies) => {
  cookies.set(cookieName, locale)
  store.dispatch({ type: 'SET_LOCALE', locale })
}
import React from 'react'
import i18n from './your-configuration-i18n-path'

const LocaleComponent => (props) => {
  return (
    <div {...props}>
      <a onClick={i18n.change('en_US')}>English</a> |
      <a onClick={i18n.change('fr_FR')}>French</a>
    </div>
  )
}

export default LocaleComponent