EPeak Daily

How to decide on a library for translating your JavaScript apps


Within the earlier articles, we’ve got seen the way to carry out localization on the back-end. Particularly, we’ve lined Rails and Phoenix frameworks. Immediately, nevertheless, we’re going to discuss libraries for translating JavaScript apps and briefly see them in motion.

It seems that there are numerous accessible options, so chances are you’ll ask: “Which one ought to I exploit?”. The obvious (and maybe the sanest) reply can be: “It relies upon”. Ideally, it is best to examine every library after which determine which one you like.

style="display:block; text-align:center;" data-ad-format="fluid" data-ad-layout="in-article" data-ad-client="ca-pub-4791668236379065" data-ad-slot="8840547438">

Due to this fact, on this article I offers you a basic introduction to the next options:

  • Globalize
  • I18subsequent
  • jQuery.I18n
  • Polyglot.js

Notice that we are going to be speaking about localizing vanilla JS apps, not about some particular client-side framework. Additionally, we received’t dive deep into every library as a result of the article would change into a lot, for much longer. I’ll solely provide you with a mild introduction to every instrument. Then we’ll attempt to examine them and are available to some basic conclusion.

We could begin?


Globalize is a fancy translation and localization JS library initially launched by jQuery crew. This library makes use of Unicode frequent locale information repository (CLDR) and has a lot of options together with:

  • Message formatting
  • Date/time parsing and the power to work with relative time
  • Pluralization help
  • Numbers parsing and foreign money formatting
  • Means to work with models (days, minutes, seconds, miles per hour and many others)

Globalize works persistently in browser and NodeJS, has a modular code and permits to require as little modules as wanted. Whereas counting on CLDR information, it doesn’t host or hardcode it instantly. Builders might select which information to load. This additionally means you can replace CLDR information your self, with out ready for a brand new model of Globalize to be launched. Chances are you’ll learn a bit extra about Globalize’s options right here.

Now let’s see this library in motion. There’s a Getting began information that explains the way to set up all of the required modules in your machine utilizing a package deal supervisor. Nevertheless, we’ll select a extra advanced method of loading every little thing manually.

Getting CLDR Information

CLDR is absolutely large and so there isn’t a cause to obtain all its content material. Fortunately, Globalize documentation summarizes what you must load when utilizing particular modules. Additionally, there’s an on-line instrument the place you simply choose the modules that will probably be used after which see what JSON recordsdata it is advisable to load. On this demo, I’ll solely use “core”, “message”, and “plural” modules, subsequently, we require the next recordsdata:

To be taught extra about how CLDR is organized, discuss with this doc. It could appear advanced at first however in actuality, issues are fairly easy: you simply cherry-pick the required recordsdata, obtain them and use in your undertaking.

I’ve positioned the recordsdata talked about above to the cldr/supplemental folder of my undertaking however chances are you’ll manage them in a different way in fact.

The following query is: how will we truly load this information? Effectively, there are two options: by embedding it contained in the Globalize.load operate or by utilizing an asynchronous $.get() methodology. The second possibility is far more sturdy, so let’s create a brand new JS file with the next content material:

// i18n.js $.when( $.get("cldr/supplemental/likelySubtags.json"), $.get("cldr/supplemental/ordinals.json"), $.get("cldr/supplemental/plurals.json"), ).then(operate() { // Normalize $.get outcomes, we solely want the JSON, not the request statuses. return [].slice.apply(arguments, [0]).map(operate(consequence) { return consequence[0]; }); }).then(Globalize.load).then(operate() { // your Globalize code right here });

On this instance, we’re loading JSON information and feed it to Globalize. We’re utilizing guarantees, so the customized code must be positioned into the second then and will probably be executed as quickly as every little thing is loaded efficiently. Be happy to refactor this code with out utilizing jQuery.

Loading Different Information

After loading CLDR JSON recordsdata, you require a bunch of different scripts:

  • jQuery (observe by the best way that Globalize itself just isn’t jQuery-based)
  • Globalize JS core module
  • Every other modules that you simply want to use in your app

jQuery and Cldr.js are exterior dependencies and chances are you’ll load them from a CDN (for instance, from cdnjs.com).

Then obtain Globalize from the Releases part. Open the dist folder. Decide all of the recordsdata that you simply require and place them beneath the globalize listing.

After that load all of the scripts within the correct order:

<!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <physique> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.5.1/cldr.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.5.1/cldr/occasion.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.5.1/cldr/supplemental.min.js"></script> <script src="globalize/globalize.js"></script> <script src="globalize/plural.js"></script> <script src="globalize/message.js"></script> <script src="i18n.js"></script> </physique> </html>

All in all, that is it. Now chances are you’ll discuss with the API part of the Globalize docs and see what capabilities chances are you’ll make the most of.

Utilizing It

You possibly can present translation messages with the assistance of loadMessages operate:

$.when( // ... }).then(Globalize.load).then(operate() { Globalize.loadMessages({ "en": { 'welcome': 'Welcome, {identify}!' } }); });

Then instantiate Globalize with the specified locale and carry out the precise translations:

// loadMessages... var globalize = new Globalize("en"); console.log(globalize.messageFormatter('welcome')({identify: 'Username'}));

messageFormatter returns a formatted translation. As you may see from this instance, it helps interpolation, however there’s extra. Wish to introduce pluralization? Easy!

Add a brand new message:

Globalize.loadMessages({ "en": { 'welcome': 'Welcome, {identify}!', 'messages': [ "You have {count, plural,", " one {one message}", " other {{count} messages}", "}" ] } });

Notice that the message might span a number of traces however on this case, it must be outlined as an array. Right here we’re using pluralization and offering two types: singular and plural. depend is an interpolation.

Now show this message:

taskFormatter = globalize.messageFormatter("messages"); console.log(taskFormatter({ depend: 10 }));

Chances are you’ll make the most of different modules in just about the identical method.

To summarize, Globalize is a good highly effective resolution with good documentation and good help. It could require a while to set it up however working with it’s handy and intuitive.


I18subsequent is a JavaScript localization framework offering all the required instruments to translate your purposes. It has a great deal of numerous options together with:

  • Help for front-end frameworks together with React, Angular, Vue and many others
  • Helps for numerous codecs (together with Polyglot which we’ll talk about later)
  • Message formatting
  • Pluralization
  • Fallbacks
  • Means to load translation information from numerous sources
  • …and plenty of, many different utilities and plugins

Loading Required Information

To get began with I18subsequent chances are you’ll merely require it from CDN, for instance:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <physique> <script src="https://cdnjs.cloudflare.com/ajax/libs/i18subsequent/14.0.1/i18subsequent.min.js"></script> </physique> </html>

In fact, it may be additionally put in with NPM or Yarn as defined right here.


As I already talked about above, I18subsequent means that you can load translations from the backend. You may additionally present them within the following method:

i18subsequent.init({ lng: 'en', sources: { en: { translation: { "hello": "Welcome" } } } }).then(operate(t) { // able to go! });

Notice that I’m additionally setting English as a default locale.

There are lots of different configuration choices which are listed on the corresponding web page.

Utilizing It

Chances are you’ll carry out translations within the following method:

// ... init .then(operate(t) { // initialized and able to go! console.log(i18subsequent.t('hello')); });

t is a operate to lookup translation based mostly on the supplied key. It will possibly additionally work with interpolation, as an illustration:

i18subsequent.t('hello', {identify: 'Username'});

Pluralization is supported too. To begin utilizing it, outline singular and plural types within the following method:

{ "msg": "one message", "msg_plural": "{{depend}} messages" }

Notice the _plural half that must be supplied for plural types. Some languages require a number of types. On this case use _0, _1, and different post-fixes, for instance:

{ "key_0": "zero", "key_1": "singular", "key_2": "two", "key_3": "few", "key_4": "many", "key_5": "different" }

Then simply use the t operate once more:

i18subsequent.t('msg', {depend: 10});

I18subsequent means that you can present context for the interpretation. That is notably essential when working with gender data:

{ "buddy": "A buddy", "friend_male": "A boyfriend", "friend_female": "A girlfriend" }

_male and _female listed below are contexts you can set within the following method:

i18subsequent.t('buddy'); // ==> No context right here, so return "A buddy" i18subsequent.t('buddy', { context: 'male' }); // -> A context is current, so return "A boyfriend"

Don’t hesitate to browse different examples within the I18subsequent’s docs on the way to allow nesting in translations, work with objects, or setup fallbacks.

To summarize, I18subsequent is a good framework with an array of assorted plugins and utilities. This framework is kind of massive and heavy, however you obtain all the required localization instruments that may be prolonged as crucial. Furthermore, setting this framework up is easy and requires little or no time. So, I’d say this can be a nice candidate for advanced purposes!


jQuery.I18n is yet one more standard resolution introduced to you by Wikimedia Engineering crew permitting to translate your JavaScript purposes. Wikimedia, in flip, is an organization behind Wikipedia undertaking, one of the vital standard web sites on the planet. jQuery.I18n is utilized in Wikipedia internally, so that you might be positive this library received’t be deserted out of the blue. It makes use of a JSON-based localization format and helps the next options:

  • Means to meta data and doc your messages
  • Helps pluralization with the assistance of CLDR
  • Gender data
  • Help for grammar types
  • Fallback chains
  • Means to customise message parser
  • Has modular code

Let’s see jQuery.I18n in motion now.

Loading Required Information

Initially, obtain the library itself and initialize its dependencies:

$ git clone https://github.com/wikimedia/jquery.i18n.git $ cd jquery.i18n $ git submodule replace --init

jquery.i18n/src folder incorporates the library’s recordsdata. Decide the modules that you simply want (on the very least, you’ll require the core jquery.i18n.js) and place them to your software. The concept right here is just like the one in Globalize. The languages folder incorporates some helpers for numerous locales. In case you are supporting one among these, don’t neglect to repeat the corresponding file as nicely.

In case your software works with plural types, then the CLDRPluralRuleParser.js file is critical too (it may be discovered beneath the jquery.i18nlibsCLDRPluralRuleParsersrc path).

After you’re prepared, load the recordsdata within the correct order, for instance:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <physique> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="lib/CLDRPluralRuleParser.js"></script> <script src="lib/jquery.i18n.js"></script> <script src="lib/jquery.i18n.messagestore.js"></script> <script src="lib/jquery.i18n.fallbacks.js"></script> <script src="lib/jquery.i18n.language.js"></script> <script src="lib/jquery.i18n.parser.js"></script> <script src="lib/jquery.i18n.emitter.js"></script> <script src="lib/jquery.i18n.emitter.bidi.js"></script> </physique> </html>

Offering Translations

As talked about above, translations for the jQuery.I18n library are saved inside JSON recordsdata. Chances are you’ll separate translation information for various languages, or retailer every little thing in a single file. Create a i18n/i18n.json file with the next contents:

{ "@metadata": { "authors": [ "Ilya" ], "last-updated": "2019-01-29", "message-documentation": "qqq" }, "welcome": "Hello!" }

To load this file, use the next code (observe that I’m additionally offering a default locale):

// most important.js jQuery(doc).prepared(operate() { $.i18n({locale: 'en'}).load({ en: 'i18n/i18n.json' }).performed(operate() { // success }) });

Embody this script in your most important web page and you’re good to go!

Utilizing It

As an example, chances are you’ll output a welcoming message within the following method:

console.log($.i18n('welcome', 'Username'));

Pluralization is carried out within the following method:

{ "msg": "You will have $1 {messages}" }

So, you’ve one key that lists all of the accessible types, each plural, and singular. $1 is a placeholder for the interpolation. You will have as many placeholders as wanted, and they need to be named in a sequential method: $2, $3 and many others.

Then simply make the most of this new key:

$.i18n('msg', 10); // $1 placeholder can have a worth of 10

The context of the interpretation is outlined in just about the identical method. For instance, you may work with gender data:

"buddy": "Some textual content... {A girlfriend}"

Present the context:

$.i18n('buddy', 'feminine');

One fascinating function is the help for the data-* HTML5 attributes. You simply want so as to add a data-i18n attribute to your tags, present the important thing as the worth, after which apply .i18n() operate on to these components or their father or mother. For instance:

<physique> <p data-i18n="translation-key">Fallback textual content goes right here</p> <p data-i18n="another-key">Fallback textual content goes right here</p> </physique>

Now inside your code merely say:


The script goes to traverse all components inside physique and exchange their contents with the messages beneath the supplied translation keys. If the important thing can’t be discovered, the preliminary content material will probably be displayed as a fallback.

jQuery.I18n is a strong and fairly easy-to-use library. Principally, chances are you’ll name it a direct competitor to Globalize as these two options have related performance. To some folks, Globalize could appear extra favorable because it doesn’t depend on jQuery. Then again, many web sites do requite jQuery, in order that’s maybe not a deal-breaker. If you happen to’d prefer to largely keep away from CLDR then jQuery.I18n is, in fact, a greater possibility. This library additionally permits to retailer metadata inside your translation recordsdata, helps data-* attributes API, helps so-called “magic phrases”, and extra. So, as you see, there’s actually a number of options!


The final resolution we’ll discuss is Polyglot.js created by Airbnb. So long as Airbnb service is worldwide, it’s important for them to have correct localization. Polyglot, in distinction to the beforehand mentioned libraries, is a really small resolution actually. It has solely the next options:

  • Fundamental translation options
  • Interpolation
  • Pluralization

It could change into a superb candidate for smaller and fewer intricate apps that don’t require all of the complexities of, say, Globalize. Now let’s see the way to get began with Polyglot!

Loading Information

Polyglot has no exterior dependencies in any respect, so all it is advisable to do is hook up the primary file:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <physique> <script src="https://cdnjs.cloudflare.com/ajax/libs/polyglot.js/2.2.2/polyglot.min.js"></script> </physique> </html>

Offering Translations and Utilizing It

Now we will present translations (aka “phrases”) and set the default locale:

var polyglot = new Polyglot({ locale: 'en', phrases: { "message_count": "%{smart_count} message |||| %{smart_count} messages" } });

On this instance the default locale is English. Additionally, there’s a message_count key that gives singular and plural types separated with four pipelines (for different languages there could also be extra types). Oddly sufficient, pluralization depends on the smart_count interpolated worth, so you will need to present it within the following method:

console.log(polyglot.t('message_count', {smart_count: 2}));

That is it! There may be not a lot else to say concerning the translation course of, because it depends solely on the t operate. Chances are you’ll discover some extra examples of utilizing Polyglot within the official doc.

Summing All the pieces Up

Probably, there’s a number of completely different options to check (some could also be kind of related on your setup), however here’s a transient abstract of the mentioned options:

A few issues to notice:

  • I18subsequent does help numerous formatting nevertheless it requires exterior dependencies like second.js
  • jQuery.I18n requires CLDR Parser just for pluralization
  • I18subsequent gives a lot of plugins to attach with the client-side framework, however different options can play properly with frameworks as nicely (chances are you’ll simply have to spend extra time to combine every little thing)
  • Chances are you’ll work with gender data (and, extra broadly talking, with contexts) in any library — it simply could also be much less handy and current extra complexities

From my expertise, I18subsequent is a really highly effective and feature-rich instrument you can simply get began with. On the identical time, Globalize’s modular method and relation on CLDR is perhaps handy, particularly for bigger and extra advanced purposes. I’ve not used jQuery.I18n that a lot however so long as the Wikimedia crew makes use of it, one can conclude that that is additionally a possible instrument with huge performance. And, Polyglot is a pleasant tiny helper for less complicated apps that additionally performs very properly with server-side frameworks like Rails.

Make Your Life Simpler With Lokalise

Supporting a number of languages on an enormous web site might change into a severe ache. You will need to be sure that all of the keys are translated for each locale. Fortunately, there’s a resolution to this downside: the Lokalise platform that makes working with the localization recordsdata a lot less complicated. Let me information you thru the preliminary setup which is nothing advanced actually.

  • To get began, seize your free trial
  • Create a brand new undertaking, give it some identify, and set English as a base language
  • Click on “Add Language Information”
  • Add translation recordsdata for all of your languages
  • Proceed to the undertaking, and edit your translations as wanted
  • You may additionally contact an expert translator to do the job for you
  • Subsequent merely obtain your recordsdata again
  • Revenue!

Lokalise has many extra options together with help for dozens of platforms and codecs, and even the chance to add screenshots to learn texts from them. So, stick to Lokalise and make your life simpler!


On this article, we have been speaking concerning the accessible instruments used to translate JavaScript purposes. We’ve lined Globalize, I18subsequent and jQuery.I18n (bigger and extra advanced options), in addition to Polyglot which gave the impression to be a a lot less complicated and smaller library. We’ve in contrast these libraries and got here up with some conclusions about them. Hopefully, now it is possible for you to to choose an I18n resolution that solely fits you. Don’t be afraid to analysis, experiment, and finally select the instrument that works for you! In spite of everything, will probably be extra sophisticated to modify to a different localization library when your software is half-finished.

I thanks for staying with me, and till the following time!

Supply hyperlink

Comments are closed.

Hey there!

Sign in

Forgot password?

Processing files…