Translating JavaScript apps

Libraries and frameworks to translate JavaScript apps

In our previous discussions, we delved into localization strategies for backend frameworks, particularly Rails and Phoenix. Today, we shift our focus to the front-end, and talk on how to translate JavaScript applications. The landscape here is rich with options, leading many to wonder: “Which library is best suited for my needs?” The answer, though often unsatisfying, truly is: “It depends.”

Localization needs can vary dramatically based on project requirements, and each library offers unique strengths. To help you navigate these waters, this article provides a primer on several prominent JavaScript localization libraries, helping you identify which might align best with your project’s specific demands.

We will cover these notable solutions:

  • Globalize: Deeply rooted in the JavaScript ecosystem with comprehensive formatting capabilities.
  • I18next: Flexible and extensible, with robust support for multi-framework integration.
  • LinguiJS: Modern and efficient, offering seamless integration with React and other frameworks.
  • jQuery.I18n: Backed by Wikimedia, ideal for projects already leveraging jQuery.
  • Polyglot.js: A minimalist library by Airbnb, perfect for simpler applications.

It’s important to note that our focus will be on vanilla JavaScript applications. This discussion is intended to give you a broad overview without delving into the complexities of each library—keeping it concise yet informative. By the end, we aim to provide a comparative insight that helps you make a well-informed decision.

So, let’s begin our exploration into the world of JavaScript localization. Shall we dive in?

If you are interested in how to translate your HTML easily, please check my other tutorial on the topic.

    JavaScript translation and localization solutions

    Translating JavaScript apps with Globalize

    Globalize, developed by the jQuery team, offers a comprehensive solution for JavaScript translation and localization. Leveraging the Unicode Common Locale Data Repository (CLDR), this library stands out with its robust features designed to cater to a wide range of linguistic needs:

    • Message Formatting: Craft localized messages with ease.
    • Date/Time Parsing: Handle dates and times efficiently, including support for relative times.
    • Pluralization Support: Accurately manage singular and plural forms.
    • Numerical Parsing and Currency Formatting: Work smoothly with numbers and monetary values.
    • Unit Handling: Convert and format units like days, minutes, and miles per hour.

    Globalize ensures consistent performance across both browser and Node.js environments. Its modular architecture means you only load what you need, keeping your application lightweight. Unlike other libraries that hardcode locale data, Globalize allows you to dynamically load CLDR data. This means you can update your localization data on-the-fly without waiting for library updates.

    To start using Globalize, check out the Getting started guide which details the installation process. For those who prefer a hands-on approach, let’s dive into manually loading the necessary data.

    Selecting CLDR data

    Considering the extensive size of the CLDR, it’s practical to download only the necessary segments. The Globalize documentation helps identify essential files for specific functionalities. For basic features like messaging and pluralization, you’ll need:

    Organize these files in your project’s cldr/supplemental directory, or structure them as suits your setup best.

    To learn more how CLDR is organized, refer to this doc. It may seem complex at first but in reality things are quite simple: you just cherry-pick the required files, download them and use in your project.

    I’ve placed the files mentioned above to the cldr/supplemental folder of my project but you may organize them differently of course.

    Loading CLDR data

    You can load your CLDR data into Globalize either by embedding it directly within the Globalize.load() function or by fetching it asynchronously with $.get(). The latter is particularly effective for managing larger data sets and ensures your application remains responsive.

    Here’s a simple example to get you started:

    // i18n.js
    
    $.when(
      $.get("cldr/supplemental/likelySubtags.json"),
      $.get("cldr/supplemental/ordinals.json"),
      $.get("cldr/supplemental/plurals.json"),
    ).then(function() {
      // Normalize $.get results, we only need the JSON, not the request statuses.
      return [].slice.apply(arguments, [0]).map(function(result) {
        return result[0];
      });
    }).then(Globalize.load).then(function() {
      //  your Globalize code here
    });

    In this example we’re loading JSON data and feed it to Globalize. We’re using promises, so the custom code should be placed into the second then and will be executed as soon as everything is loaded successfully. Feel free to refactor this code without using jQuery.

    Loading essential libraries for JavaScript translation

    Once you’ve set up the CLDR data, integrating Globalize into your JavaScript application involves loading several key libraries:

    1. jQuery: Though Globalize is not dependent on jQuery, it’s required for handling DOM and other utilities if used in your application.
    2. CLDR.js: Essential for processing CLDR data, ensuring that Globalize functions accurately.
    3. Globalize JS Core Module: The backbone of Globalize, handling the fundamental localization and internationalization functionalities.
    4. Additional Globalize Modules: Depending on your application’s needs, such as currency handling or advanced date formatting, you might need additional modules.

    Recommended sources:

    • jQuery and CLDR.js can be loaded from reputable CDNs to ensure efficiency and speed. For example, you can use cdnjs which hosts a wide range of libraries.
    • Download Globalize directly from its GitHub Releases section. Navigate to the dist folder, select the necessary files for your project, and organize them within your project structure under a globalize directory.

    Script loading sequence:

    It’s crucial to load these scripts in the correct order to avoid dependencies issues. Here’s the recommended sequence:

    <!-- index.html -->
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    </head>
    <body>
    
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.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/event.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>
    </body>
    </html>
    

    This is it. Now you may refer to the API section of the Globalize docs and see what functions you may utilize.

    Implementing translations with Globalize

    Setting up translation messages

    Begin by loading your translation messages using the loadMessages function. This can be done seamlessly within your code flow using jQuery’s when and then methods:

    $.when(
      // load necessary CLDR data here...
    ).then(Globalize.load).then(function() {
      Globalize.loadMessages({
        "en": {
          'welcome': 'Welcome, {name}!'
        }
      });
    });

    Initializing and using Globalize:

    Once your messages are loaded, instantiate Globalize with your preferred locale to start translating:

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

    The messageFormatter function allows you to interpolate variables such as {name} in the example above, making your messages dynamic and adaptable.

    Implementing pluralization:

    Globalize also supports pluralization directly in messages. Here’s how to include singular and plural forms:

    Globalize.loadMessages({
      "en": {
        'welcome': 'Welcome, {name}!',
        'messages': [
          "You have {count, plural,",
          "    one {one message}",
          "  other {{count} messages}",
          "}"
        ]
      }
    });
    
    var taskFormatter = globalize.messageFormatter("messages");
    
    console.log(taskFormatter({
      count: 10
    }));

    In the example above, the message structure handles both singular and plural cases based on the count. Notice how the message is defined as an array to accommodate multiple lines for clarity.

    Localizing dates:

    To localize date formats using Globalize, you first need to load the necessary CLDR data related to dates. Then, you can use Globalize to format dates according to the local standards of the user’s region. Here’s how you can set it up:

    // Load the necessary CLDR data first
    Globalize.load(
      cldrData.entireSupplemental(),
      cldrData.entireMainFor('en', 'es')
    );
    
    // Instantiate Globalize
    var globalizeEn = new Globalize('en');
    var globalizeEs = new Globalize('es');
    
    // Example date
    var date = new Date();
    
    // Format date in English
    console.log(globalizeEn.formatDate(date, { datetime: "medium" }));
    
    // Format date in Spanish
    console.log(globalizeEs.formatDate(date, { datetime: "medium" }));

    This code snippet demonstrates how to format dates in English and Spanish, but you can adapt it to any supported locale by loading the appropriate CLDR data and creating a Globalize instance for that locale.

    Localizing currency:

    For currency formatting, Globalize can also make your app adaptive to different economic regions. You’ll need to load some currency data and then use Globalize to format numbers as currency values. Here’s a practical example:

    // Load necessary CLDR data
    Globalize.load(
      cldrData.entireSupplemental(),
      cldrData.entireMainFor('en', 'ja')
    );
    
    // Instantiate Globalize
    var globalizeEn = new Globalize('en');
    var globalizeJa = new Globalize('ja');
    
    // Example amount
    var amount = 123456.78;
    
    // Format currency in USD for English locale
    console.log(globalizeEn.formatCurrency(amount, "USD"));
    
    // Format currency in JPY for Japanese locale
    console.log(globalizeJa.formatCurrency(amount, "JPY", { style: "accounting" }));

    In this example, formatCurrency is used to show how $123,456.78 is formatted in U.S. dollars for English users and in Japanese yen for Japanese users, using the accounting style for the latter.

    Summary

    While the initial setup of Globalize might take some time, it’s a robust solution designed for comprehensive JavaScript application internationalization. Its detailed documentation and flexible features make it an excellent choice for developers aiming to enhance their applications’ global reach.

    Streamlining JavaScript Translation with I18next

    I18next is a comprehensive JavaScript localization framework designed to translate and localize applications efficiently. It’s compatible with multiple front-end frameworks like React, Angular, and Vue, making it versatile for various development environments.

    Key features:

    • Framework Support: Integrates smoothly with major front-end frameworks.
    • Format Flexibility: Handles different data formats, including Polyglot.
    • Dynamic Message Formatting and Pluralization: Easily manage singular and plural forms.
    • Resource Loading: Load translation data from multiple sources, enhancing flexibility.
    • Extensive Plugin System: Offers numerous plugins and utilities for advanced localization needs.

    Loading required files

    To incorporate I18next into your project, you can link it directly via CDN:

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

    Alternatively, you can install it using NPM or Yarn for more control over versioning and dependencies.

    Configuration and usage

    Setting up I18next is straightforward. You can start by initializing it with basic settings, like so:

    i18next.init({
      lng: 'en',  // Sets English as the default locale
      resources: {
        en: {
          translation: {
            "hi": "Welcome, {name}"
          }
        }
      }
    }).then(function(t) {
      console.log(i18next.t('hi', { name: 'Username' }));
    });
    

    This setup includes a basic greeting that utilizes variable interpolation.

    • I am setting English as a default locale.
    • I18next also enables you to load translations from the backend
    • t (translate) is a function to look up translation based on the provided key.
    • There are many other configuration options that are listed on the corresponding page.

    I18next also supports:

    • Pluralization: Define messages for singular and plural cases.
    • Contextual Translations: Handle variations like gender or formal/informal addressing.
    • Nested Translations and Fallbacks: Manage complex translation scenarios and ensure fallbacks for missing translations.

    Implementing pluralization

    Let’s see how to implement pluralization. To start using it, define singular and plural forms in the following way:

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

    Note the _plural part that has to be provided for plural forms. Some languages require multiple forms. In this case use _0, _1, and other post-fixes, for example:

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

    Then just use the t function again:

    i18next.t('msg', {count: 10});

    Providing translation context

    I18next allows you to provide context for the translation. This  is particularly important when working with gender information:

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

    _male and _female here are contexts that you can set in the following way:

    i18next.t('friend'); // ==> No context here, so return "A friend"
    i18next.t('friend', { context: 'male' }); // -> A context is present, so return "A boyfriend"

    Localizing dates

    Let’s see how to localize date and time. First, translations:

    {
      "intlDateTime": "On the {{val, datetime}}",
    }

    Now use these translations in the following way:

    i18next.t('intlDateTime', { val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)) });
    // --> On the 12/20/2012
    i18next.t('intlDateTime',
              {
                val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)),
                formatParams: {
                  val: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },
                },
              });
    // --> On the Thursday, December 20, 2012

    Localizing currency

    I18next can also be used to localize currencies. First, define your JSON:

    {
      "intlCurrencyWithOptionsSimplified": "The value is {{val, currency(USD)}}",
      "intlCurrencyWithOptions": "The value is {{val, currency(currency: USD)}}",
      "twoIntlCurrencyWithUniqueFormatOptions": "The value is {{localValue, currency}} or {{altValue, currency}}",
    }

    Now simple utilize these keys:

    i18next.t('intlCurrencyWithOptionsSimplified', { val: 2000 });
    // --> The value is $2,000.00
    i18next.t('intlCurrencyWithOptions', { val: 2300 });
    // --> The value is $2,300.00
    i18next.t('twoIntlCurrencyWithUniqueFormatOptions',
              {
                localValue: 12345.67,
                altValue: 16543.21,
                formatParams: {
                  localValue: { currency: 'USD', locale: 'en-US' },
                  altValue: { currency: 'CAD', locale: 'fr-CA' },
                },
              },);
    // --> The value is $12,345.67 or 16 543,21 $ CA

    Don’t hesitate to browse other examples in the I18next’s docs on how to enable nesting in translations, work with  objects, or setup fallbacks.

    Summary

    I18next is not just powerful but also adaptable, fitting well into modern JavaScript projects. While it’s packed with features, its initial setup is simple and the learning curve is moderate, making it an excellent choice for applications requiring robust localization capabilities. For more detailed configurations and examples, the I18next documentation is a rich resource.

    Translate JavaScript apps with LinguiJS

    LinguiJS is a cutting-edge framework designed for simplifying the internationalization process of JavaScript applications. It’s particularly well-suited for React but can be used in any JavaScript project. Developed with modern web development practices in mind, LinguiJS stands out for its developer-friendly approach and its ability to produce highly readable and maintainable code.

    Key features of LinguiJS:

    • Developer-Friendly API: LinguiJS offers a straightforward API that integrates seamlessly into modern JavaScript workflows. Developers can add translations without cluttering their code, making it more maintainable and less prone to errors.
    • Compile-Time Optimizations: The framework compiles translations to optimized JavaScript bundles during the build process. This ensures that loading translations is fast and efficient, reducing the runtime overhead commonly associated with dynamic translation loading.
    • Support for Multiple Formats: LinguiJS allows developers to maintain their translation catalogs in multiple formats such as JSON, JavaScript, or PO files. This flexibility makes it easier to integrate with various tools and workflows.
    • Pluralization and Formatting: Complex language features like pluralization, number formatting, and date formatting are built into the framework. LinguiJS handles these with ease, providing tools to manage different linguistic nuances across languages.
    • Rich Macros and Components: For React developers, LinguiJS provides a set of rich macros and components that make it easy to wrap text in translatable components. These tools automatically handle rendering based on the current locale without additional boilerplate.

    Why choose LinguiJS?

    LinguiJS is particularly beneficial for projects where readability and ease of maintenance are priorities. It aligns well with modern development tools and practices, supporting hot-reloading and code splitting out of the box. The framework’s design also emphasizes minimal impact on bundle size, making it suitable for performance-sensitive applications.

    In summary, LinguiJS is an excellent choice for developers looking for a robust, efficient, and easy-to-use solution to manage the internationalization of their JavaScript applications. Its comprehensive feature set and developer-oriented design make it a standout choice in the realm of JavaScript i18n solutions.

    Installing and setting up LinguiJS

    To install LinguiJS, you can use NPM:

    npm install --save-dev @lingui/cli @lingui/macro babel-plugin-macros @babel/core
    npm install --save @lingui/core

    Then setup your project:

    import { i18n } from "@lingui/core";
    
    // messages.js is generated by the cli
    import { messages } from "path-to-locale/en/messages.js";
    
    i18n.load("en", messages);
    i18n.activate("en");

    Using LinguiJS

    Now you are ready to use the solution in the following way:

    import { t } from "@lingui/macro";
    
    t`Hello World!`;
    // becomes "Salut le monde!"
    
    const name = "Fred";
    t`My name is ${name}`;
    // becomes "Je m'appelle Fred"

    Note that you can take advantage of the extractor tool to scan your project and extract translations easily:

    npx lingui extract

    Pluralization can also be easily implemented:

    import { plural } from "@lingui/macro";
    
    const count = 42;
    
    plural(count, {
      one: "# book",
      other: "# books",
    });
    // becomes "42 livres"

    Conclusion

    LinguiJS stands out in the landscape of JavaScript internationalization libraries due to its ease of use, efficiency, and tight integration with modern development workflows. Designed with simplicity and performance in mind, it offers developers a robust solution for adding multilingual support to their applications without sacrificing speed or flexibility.

    By streamlining the translation process with tools for automatic message extraction and compilation, LinguiJS helps maintain a clear separation between coding and translation tasks. This separation enhances collaboration in multi-disciplinary teams and supports agile development practices. Whether you’re building a small web app or a large-scale enterprise application, LinguiJS adapts to your needs, enabling you to deliver a localized experience that resonates with users globally.

    In summary, LinguiJS is more than just a library; it’s a comprehensive internationalization framework that empowers developers to build truly global applications. Its developer-friendly approach ensures that internationalizing your application is a smooth and rewarding experience.

    Enhancing JavaScript localization with jQuery.i18n

    Developed by the Wikimedia Engineering team, the minds behind Wikipedia, jQuery.i18n is a robust library designed for translating JavaScript applications. Given its deployment on one of the world’s most visited websites, you can trust its stability and ongoing support. This JSON-based localization tool supports a wide array of features:

    • Meta Information: Document your messages for better maintainability.
    • Pluralization: Integrated with CLDR for handling multiple plural forms.
    • Gender-Specific Information: Customize messages based on gender.
    • Grammar Forms: Support for complex language rules.
    • Fallback Chains: Ensure messages degrade gracefully.
    • Customizable Message Parsing: Tailor the parser to fit your specific needs.
    • Modular Architecture: Include only the components you need.

    Let’s see jQuery.I18n in action now.

    Getting started with jQuery.i18n:

    To integrate jQuery.i18n into your project, start by cloning the repository and setting up its dependencies:

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

    Navigate to the jquery.i18n/src directory. This folder contains all necessary library files. For basic functionality, include at least the core jquery.i18n.js. If your application supports various locales, also include the appropriate helper files from the languages folder.

    If you’re utilizing plural forms, ensure to include the CLDRPluralRuleParser.js, which is located under jquery.i18n/libs/CLDRPluralRuleParser/src.

    Loading the libraries:

    Here’s how you can load jQuery.i18n along with its modules in your HTML file:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
    </head>
    
    <body>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.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>
    </body>
    
    </html>
    

    Providing translations with jQuery.i18n

    Using jQuery.i18n, translations are typically managed within JSON files, allowing for easy updates and maintenance. This approach supports separating translation data by language or combining it all in one file, depending on your project’s needs.

    Create a JSON file to store your translations. For example, you might have a file named i18n.json located in an i18n folder. Here’s a simple example of what this file might look like:

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

    This format allows you to include metadata about the file, such as the authors and last update date, which can be helpful for maintaining and tracking changes.

    Loading translation files:

    To make these translations available in your application, you’ll need to load them appropriately using jQuery.i18n. Here’s how you can do it within a JavaScript file, such as main.js:

    // main.js
    
    jQuery(document).ready(function() {
      $.i18n({locale: 'en'}).load({
        en: 'i18n/i18n.json'
      }).done(function() {
        // success
      })
    });
    

    Include this script on your main page and you are good to go!

    Using jQuery.i18n to translate JavaScript apps

    With jQuery.i18n, displaying translated messages in your application is straightforward. For instance, to show a welcoming message, you can use:

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

    In this example, ‘welcome’ is the key from your JSON file that corresponds to the welcome message, and ‘Username’ is a dynamic parameter passed into the message.

    Handling pluralization:

    jQuery.i18n supports pluralization directly within the translation strings using special placeholders and conditions:

    {
      "msg": "You have $1 {{PLURAL:$1|message|messages}}"
    }

    Here, $1 is a placeholder that will be replaced by the actual number you pass to the function. Depending on the number, jQuery.i18n will choose either “message” (singular) or “messages” (plural).

    Utilize this key in your script like so:

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

    Contextual translations:

    jQuery.i18n also allows for contextual translations such as gender specifics:

    "friend": "Some text... {{GENDER:$1|A boyfriend|A girlfriend}}"

    When using this key, provide the context to get the appropriate translation:

    $.i18n('friend', 'female');

    Automatic localization using data attributes:

    An efficient feature of jQuery.i18n is its ability to automatically localize text elements using data-i18n attributes in your HTML:

    <body>
      <p data-i18n="translation-key">Fallback text goes here</p>
      <p data-i18n="another-key">Fallback text goes here</p>
    </body>
    
    <script>
      $('body').i18n(); // Automatically updates text based on the data-i18n attribute
    </script>
    

    This setup allows jQuery.i18n to scan the HTML, find all elements with a data-i18n attribute, and replace their content with the correct translated text. If a translation for a key isn’t found, the original text (‘Fallback text goes here’) is used instead.

    Summary

    jQuery.i18n is a versatile and user-friendly library for localizing JavaScript applications. It stands out with features like support for pluralization, contextual translations, and HTML5 data attributes, making it a strong choice for projects that may already be using jQuery. Whether you prefer jQuery.i18n or another library like Globalize might depend on your specific project requirements and whether you need to minimize external dependencies like jQuery.

    Either way, jQuery.i18n offers a comprehensive set of tools for managing your application’s localization needs efficiently.

    Translate JavaScript apps with Polyglot

    Created by Airbnb, Polyglot.js is tailored for global service delivery, reflecting Airbnb’s extensive international user base. Polyglot.js stands out due to its minimalistic approach, focusing on core localization functionalities without the overhead of larger libraries. This makes it an ideal choice for smaller applications or projects that require straightforward localization capabilities.

    Key features of Polyglot.js:

    • Basic Translation: Handles the essentials of translating text.
    • Interpolation: Allows for dynamic content within translations.
    • Pluralization: Supports basic singular and plural distinctions.

    Getting started with Polyglot.js:

    Polyglot.js is designed to be lightweight and dependency-free, simplifying integration into any project. Here’s how you can include it in your HTML:

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

    Implementing translations with Polyglot.js

    Polyglot.js simplifies the process of adding translations (“phrases”) and setting the default locale in your application. Here’s a concise guide on how to use these features effectively.

    Initialize Polyglot with the desired locale and the necessary phrases for translation:

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

    In this setup:

    • locale specifies the default language, which is English (en) in this case.
    • phrases contains all the keys and their translations. The message_count key demonstrates how to handle both singular and plural forms. The four pipelines (||||) separate the two forms.

    Using translations:

    To retrieve and display these translations, use Polyglot’s t function, which handles text translation based on the provided key and interpolation values:

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

    In this example, smart_count is used to determine whether to use the singular or plural form of the word “message”. This method is particularly useful for languages with more complex pluralization rules, where multiple forms might be needed.

    Additional usage tips:

    While the basics of Polyglot.js are simple, it supports more advanced features which can be found in the official Polyglot documentation. These include handling multiple plural forms for languages with different grammatical rules, and using nested translations for more complex language structures.

    Summary

    Polyglot.js offers a straightforward approach to implementing localization in JavaScript applications. Its simplicity is especially advantageous for smaller projects or applications that require basic translation functionalities without the overhead of more complex libraries. By focusing on key features like interpolation and pluralization, Polyglot.js provides a robust solution for developers looking to enhance their applications’ international reach.

    Translate JavaScript apps with Lokalise!

    Supporting multiple languages on a big website may become a serious pain. You must make sure that all the keys are translated for each and every locale. Luckily, there is a solution to this problem: the Lokalise platform that makes working with the localization files much simpler. Let me guide you through the initial setup which is nothing complex really.

    • To get started, grab your free trial
    • Create a new project, give it some name, and set English as a base language
    • Click “Upload”
    • Upload translation files for all your languages
    • Proceed to the project, and edit your translations as needed
    • You may also contact professional translator to do the job for you
    • Next simply download your files back
    • Profit!

    Lokalise has many more features including support for dozens of platforms and formats, and even the possibility to upload screenshots in order to read texts from them. So, stick with Lokalise and make your life easier!

    Conclusion

    Throughout this article, we’ve explored a variety of tools designed to translate and localize JavaScript applications. From the comprehensive capabilities of Globalize, I18next, and jQuery.I18n to the simplicity and efficiency of Polyglot.js, we’ve examined a spectrum of solutions each suited to different project needs. Additionally, we also looked at LinguiJS, which stands out with its modern approach and ease of integration, especially for projects utilizing React.

    Each library offers unique features and levels of complexity, and choosing the right one depends heavily on your specific project requirements, such as the need for support across multiple frameworks, the simplicity of the API, or the robustness of the localization features.

    Hopefully, this comparative overview has equipped you with the knowledge to select an internationalization (I18n) solution that aligns perfectly with your project’s goals. Remember, the best approach is to thoroughly research and experiment with these tools. Making an informed decision early on is crucial, as switching your localization framework mid-development can be a challenging and time-consuming process.

    Thank you for joining me in this exploration of JavaScript localization tools. Until next time, happy coding, and may your applications resonate well with audiences around the globe!

    Talk to one of our localization specialists

    Book a call with one of our localization specialists and get a tailored consultation that can guide you on your localization path.

    Get a demo

    Related posts

    Learn something new every two weeks

    Get the latest in localization delivered straight to your inbox.

    Related articles
    Localization made easy. Why wait?