3.4.1 • Published 1 month ago

inferno-translations v3.4.1

Weekly downloads
-
License
NCSA
Repository
github
Last release
1 month ago

inferno-translations

Translate inferno applications.

Features

  • Isomorphic
  • Small bundle size
  • ICU message-like syntax
  • Dynamic messages loading

Usage

  1. Install the package npm install inferno-translations
  2. Wrap your App with the TranslationsProvider component
import { hydrate } from 'inferno-hydrate'
import { BrowserRouter } from 'inferno-router'
import { TranslationsProvider } from 'inferno-translations'

import App from '../shared/components/App'
import en from '../shared/translations/en.json'

hydrate(
  <BrowserRouter>
    <TranslationsProvider language='en' messages={en}>
      <App />
    </TranslationsProvider>
  </BrowserRouter>
  , document.getElementById('root')
)
  1. The application can now be translated.

Utilize the DateTime, Numeric and Message components inside of App.

import { DateTime, Numeric, Message } from 'inferno-translations'

export default function TranslatedComponent () { 
  return (
    <>
      <DateTime />
      <Numeric />
      <Message />
    </>
  )
}

Components can also be wrapped with the withTranslations HOC to have access to the translations prop.

import { withTranslations } from 'inferno-translations'

function TranslatedComponent ({ translations }) {
  // The translateions.translate props allows translations to the current app language
  const t = translations.translate
  console.log(t('hello')) // ciao

  // The translate function also allows to translate to languages that aren't the active app language
  console.log(translations.currentLanguage) // it
  const helloNl = t('hello', null, 'nl') // hallo

  // Change language of the whole app with translator.language 
  const { translator } = translations
  translator.language('it')

  translator.formatDate()
  translator.formatNumber()
  translator.translate()
  translator.getMessageById()

  return (
    <>
      <h1 className={t('title')}><Message id='translated' /></h1>
    </>
  )
}

export default withTranslations(TranslatedComponent)

Dynamic locale data loading

  1. Create a couple of functions to handle the loading of locale data
export async function getMessages (lang) {
  const locale = await import(`./${lang}.json`)
  return locale.default
}

export async function dynamicMessagesLoading (translations, lang) {
  const { language, localeData } = translations
  // do not load anything if locale data was already loaded.
  for (let i = 0, len = localeData.length; i < len; i++) {
    if (localeData[i].language === lang) {
      return language(lang)
    }
  }

  const messages = await getMessages(lang)
  language(lang, messages)
}
  1. Use this function
import { Component } from 'inferno'
import { withTranslations } from 'inferno-translations'
import { dynamicMessagesLoading } from '../shared/translations/utils'

class LanguageSwitcherComponent extends Component {
  constructor(props) {
    super(props)
    this.handleSwitch = this.handleSwitch.bind(this)
  }

  handleSwitch (event) {
    const language = event.target.getAttribute('name');
    dynamicMessagesLoading(this.props.translations, language)
  }

  return (
    <button
      type='button'
      name='nl'
      onClick={this.handleSwitch}
    >
      <Message id='dutch' />
    </button>
  )
}

export default withTranslations(LanguageSwitcherComponent)
  • If you use SSR, you can use the classic window.___initialData trick paired with getLocaleData.
  • Remember to apply the same logic to a utility function when using the translations.translate prop for translations in non-currentLanguage languages.

Missing messages and fallback messages

When a message is missing from the messages object, translator.translate returns options.defaultMessage if provided, otherwise it will return the key of the message.

If you'd prefer for translator.translate to fallback to messages of one language that is known to be complete, you have to manually merge two messages objects and provide the result object to translator.

import en from '../shared/translations/en.json';
import nl from '../shared/translations/nl.json';

function addFallbackMessages (messages, fallback) {
  const result = { ...messages }
  const fallbackKeys = Object.keys(fallback)
  for (let i = 0, len = fallbackKeys.length; i < len; i++) {
    if (!Object.prototype.hasOwnProperty.call(messages, fallbackKeys[i])) {
      result[fallbackKeys[i]] = fallback[fallbackKeys[i]]
    }
  }
  return result
}

const nlWithEnFallbacks = addFallbackMessages(nl, en)

Notes

  • Pull requests are welcome, look here.
  • This library uses Inferno JSX, it is not pre-compiled (can change if you open a PR)