Previous implementation

In previous implementation of my project I used a mix of Backbone and React and translations were handled by jQuery.i18n.properties. Initialization was done before the first render:

translation files were kept in /js/bundle folder in .properties files with the default English values in Messages.properties:

and the actual translation logic was in a common function:

that took the key and the dynamic values used in the translations for that key. An actual example on how I used it is:

After I migrated my project completely to React, I wanted to get rid of jQuery.i18n.properties and jQuery and use something different. The first obvious choice was React Intl since it is one of the most used i18n solutions in React but I did not like it because it looked like that I had to change too much to accommodate it. I wouldn’t mind if the replacement had a completely different way to initialize itself but my expectations for the new library were:

  • to have support for .properties file, I just didn’t want to use a different format.

  • to have a similar way to use load translations so that I had to change only the localize function and everything else kept as it is.

The first library that appeared to have this was i18next and the steps are below.

Use i18next instead of jQuery.i18n.properties

Dependencies

I had to add two new npm packages:

Configuration

  • backend – I chose to load resources asynchronously because of the possibility to keep the name and the content of files unchanged.
  • loadPath – It can be a string or a function with the language the first parameter. The second parameter is the namespace but since I’m not using it in my project, I omited it. I chose to use the function just to be able to make a difference between English, with the default Messages.properties file, and the rest of the locales that have the locale as the file suffix name like Messages_ro.properties.
  • parse – A function that receives the content of the file and returns an object that has the file keys mapped as the object properties and the file translations mapped as the object properties values. Default format for i18next property files is json so I had to write a small utility, PROP.js, that does a similar job as JSON JavaScript object.

  • lng – Language to use.
  • fallbackLng – Language to use if translations in user language are not available.
  • interpolation – Configuration used to diferentiate between regular text and dynamic values placeholders. Since in jQuery.i18n.properties I used something like {0} I had to override default configurations for prefix and suffix.

Code changes

Translation common logic was updated to:

Above logic was need to accommodate the migration from a usage like:

to:

as i18next expects.

Conclusion

I liked that the needed changes were small and I could replace jQuery.i18n.properties with i18next easily without changing too much of existing code. This is how a mature library should look like.