Key Points
This article was reviewed by Julian Motz, Panayiotis Velisarakos, Vildan Softic and Tim Severien. Thanks to all SitePoint peer reviewers for getting SitePoint content to its best!
Suppose you are a developer and are working on the next hot product. Your customers love your product and it has received extremely high ratings on all social networks. Even better, the CEO has just received $10,000,000 in funding to expand into new markets. But before you go global, you must update your product to support different languages, currencies, date formats and more. What do you think? You and your team will be responsible for achieving this. From a technical point of view, your software must be internationalized and then localized.
Internationalization (also known as i18n) is the process of creating or converting products and services so that they can easily adapt to a specific local language and culture. Localization (also known as l10n) is the process of adjusting internationalized software for a specific region or language. In other words, internationalization is the process of enabling your software to support multiple cultures (currency formats, date formats, etc.), while localization is the process of implementing one or more cultures.
These two processes are often adopted by companies interested in different countries, but they may also be helpful to individual developers working on their own websites. For example, you probably know, I am Italian and I own a website. My website is currently in English, but I may decide to internationalize it and then localize it to Italian. This is very beneficial for those who are native Italian and unfamiliar with English.
In this article, I will introduce you to Globalize, a JavaScript library developed by some members of the jQuery team for internationalization and localization. All the code snippets demonstrated in this article can be found in our GitHub repository.
But before delving into Globalize, I want to end this short introduction about i18n with the words of project leader Rafael Xavier de Souza:
Developers believe that i18n is about translation into non-English languages. i18n simply needs to extend the current application to multiple countries or markets. I've been trying to explain that i18n is about "talking". Every app has to "talk" with its users at some point. To talk to users, the application may require plural support, gender variation, date formatting, digital formatting, and currency formatting. Even in English, it can be tricky to do the job correctly.
Globalize is a JavaScript library for internationalization and localization that utilizes the official Unicode CLDR JSON data.
This library is open source and is developed by Rafael Xavier de Souza and some members of the jQuery team.
Globalize Unicode Consortium-based Unicode Consortium Data Repository (CLDR), the largest and most comprehensive standard repository of locale data available. So unlike libraries that embed locale data, if you use Globalize, you can easily always use the latest CLDR data.
This library is suitable for browsers and Node.js modules. Globalize 1.0 supports all major browsers, including IE9, Chrome, Firefox, Safari 5.1, and Opera 12.1.
The main functions of this library include:
What I like most about Globalize is that it provides a module for each of its features. The developer may not need the entire library, so he can choose the modules he needs. Another interesting feature is that unlike other libraries, it keeps the code separate from the content by not hosting or embeding any locale data in the library.
But Globalize is not the only option. If you are interested in other alternatives, Rafael has a dedicated page. The most notable alternative is i18next.
This may be surprising to some of you, but JavaScript provides native support for internationalization through the Internationalization API (also known as ECMA-402). An Intl object is an object available on a window object that acts as a namespace for the internationalized API. This API currently provides methods to format numbers and dates, as well as compare strings in a specific language.
Now that you know the existence of an international API, you might think Globalize is using it behind the scenes. This approach will certainly improve the performance of date and number formatting. However, because of low and very inconsistent support among browsers, the library does not use it.
I want you to experience the international API before we continue to discuss Globalize.
The first example I will show is using the International API to format dates in multiple locales: IT, US, and GB.
// 2016 年 6 月 30 日 var date = new Date(2016, 5, 30); // "30/6/2016" console.log(new Intl.DateTimeFormat('it-IT').format(date)); // "6/30/2016" console.log(new Intl.DateTimeFormat('en-US').format(date)); // "30/06/2016" console.log(new Intl.DateTimeFormat('en-GB').format(date));
In this example, I use the specified locale ("it-IT", "en-US", and "en-GB") to create a new date formatter using the DateTimeFormat constructor. Then, I call the format method to format the date object.
The above code can also be used as JSBin.
As mentioned earlier, the API also allows you to format numbers. Here is an example using the NumberFormat constructor:
var number = 1302.93; // "1.302,93" console.log(new Intl.NumberFormat('it-IT').format(number)); // "1,302.93" console.log(new Intl.NumberFormat('us-US').format(number)); // "1,302.93" console.log(new Intl.NumberFormat('en-GB').format(number));
By looking at the output of this second code snippet (which can also be used as JSBin), you can notice that in Italy, we have different formats for numbers than in the United States and the United Kingdom.
As mentioned earlier, the support for this API is low, but if you want to use it, you can use this polyfill in your application.
Now that I have given you a better understanding of how internationalization and localization work, let’s discuss Globalize.
Globalize can be easily installed through npm:
npm install globalize cldr-data --save
This command also installs CLDR data, which is necessary to load locale data that Globalize will use (for example, in a language format for numbers or dates). After installing these two packages, we can use the library.
Note: The following example assumes that Node is used. If you are interested in using Globalize in your browser, I suggest you start with an example on the project homepage. The webpack example makes it especially easy to get up and running quickly.
Next, I will use Globalize to rewrite the two code snippets listed in the previous section.
The first example can be implemented as follows:
// 2016 年 6 月 30 日 var date = new Date(2016, 5, 30); // "30/6/2016" console.log(new Intl.DateTimeFormat('it-IT').format(date)); // "6/30/2016" console.log(new Intl.DateTimeFormat('en-US').format(date)); // "30/06/2016" console.log(new Intl.DateTimeFormat('en-GB').format(date));
Although it's simple, the above code allows me to cover several topics. When I first used Globalize, I found it a bit strange that some of the language codes used for CLDR data use only two letters. To maintain consistency, I want all locales to require full versions of the ISO 3166 standard (e.g., "it-IT" and "en-US") rather than short versions (e.g., "it" and "en"). While it seems reasonable to assume that Italian is Italian (Italian originated in Italy after all), this is confusing for English. "en" means American English, not British English. If you want to make sure you don't make the same mistakes as me, I suggest you check out this table.
Another concept worth outlining is the entireSupplemental method (the third statement of the code). This will load all files containing supplementary information for country or locale data. For example, the phone country code (39 in Italy), population, some well-known abbreviations, how to spell the currencies of other countries, etc.
The last point I want to introduce is the fourth statement, where I call the entireMainFor method. This allows loading locale data for the required country (Italy, the United States, and the United Kingdom in the example above).
For formatting numbers, Globalize provides the formatNumber method. The signature of this method is
var number = 1302.93; // "1.302,93" console.log(new Intl.NumberFormat('it-IT').format(number)); // "1,302.93" console.log(new Intl.NumberFormat('us-US').format(number)); // "1,302.93" console.log(new Intl.NumberFormat('en-GB').format(number));
where value is the number to be formatted, options is an object for custom method return value. Some examples of options you can specify include:
The complete list of available options can be found in the documentation.
Now that we have learned more about the formatNumber method, let's see how it actually applies.
npm install globalize cldr-data --save
The library provides a currencyFormatter method to help you format currency values. This method supports many options, allowing you to define whether you want to round the number, whether you want to use the symbol of the currency (such as "$") or its code (such as "USD"), and so on.
A example of using currencyFormatter() is shown below:
// 包含 Globalize 库 var Globalize = require('globalize'); // 包含 CLDR 数据 var cldrData = require('cldr-data'); // 加载补充数据 Globalize.load(cldrData.entireSupplemental()); // 加载指定语言环境的数据 Globalize.load(cldrData.entireMainFor('it', 'en', 'en-GB')); // 2016 年 6 月 30 日 var date = new Date(2016, 5, 30); // "30/6/2016" console.log(Globalize('it').formatDate(date)); // "6/30/2016" console.log(Globalize('en').formatDate(date)); // "30/06/2016" console.log(Globalize('en-GB').formatDate(date));
Solving numbers can also be a task you have to perform, such as when processing user input. The following example demonstrates how to do this:
formatNumber(value[, options])
Another very common feature in modern web applications is to display time and date in relative terms. For example, you will often find labels like "Yesterday" and "Last Week" instead of showing the full date of the day. With Globalize, this task can be easily accomplished with the relativeTimeFormatter method. Here is an example of usage:
// 2016 年 6 月 30 日 var date = new Date(2016, 5, 30); // "30/6/2016" console.log(new Intl.DateTimeFormat('it-IT').format(date)); // "6/30/2016" console.log(new Intl.DateTimeFormat('en-US').format(date)); // "30/06/2016" console.log(new Intl.DateTimeFormat('en-GB').format(date));
Globalize provides many other methods that I have not covered in this article. However, the topics presented here should provide you with enough information to help you get started. Additionally, the documentation for this library is very detailed.
In this article, I discuss what internationalization and localization are and why they are very important for expanding the market for products. I briefly introduced the internationalized API by mentioning some supported features, and then, I showed some examples of their usage.
In the second part of this article, I introduce you to Globalize, a JavaScript library developed by the jQuery team for internationalization and localization. The library is very powerful and comes with all the methods you may need to internationalize your project, such as: ways to parse numbers, format dates, and format currency values. If you think the library saves you time, feel free to give back by contributing to the project.
Again remind you that all the code snippets demonstrated in this article can be found in our GitHub repository.
Internationalization, often abbreviated as i18n, is an important aspect of web development, especially when creating applications for global audiences. It involves preparing your website or application to support multiple languages and regional differences. This is especially important in JavaScript, a language widely used in web development. By implementing i18n in JavaScript, developers can create applications that meet different user groups, thereby enhancing user experience and accessibility. It also helps localize applications, which can significantly improve the coverage and usability of applications.
i18n in JavaScript works by allowing developers to externalize locale-specific strings or messages from the application's code. These strings are then stored in separate files, often referred to as resource packages. Each resource package corresponds to a specific locale. When the application runs, it recognizes the user's locale and loads the corresponding resource package. This way, the application can display messages and content in the user's preferred language.
There are several libraries available for implementing i18n in JavaScript. Some of the most popular libraries include i18next, i18n-js, and Globalize. These libraries provide a range of features to facilitate internationalization, such as language detection, pluralization, numerical and date formatting, and more. They also support various frameworks such as React, Angular, and Vue.js, making them a versatile tool for web development.
To use the i18n-js library in your JavaScript project, you first need to install it using npm or yarn. Once installed, you can import it into your project and start using its features. This library provides functions for translating strings, formatting numbers and dates, and more. You can also define your translations in a separate JSON file, which library can load these files according to the user's locale.
Yes, i18n can be implemented in JavaScript without using libraries. This can be done by manually externalizing locale-specific strings from your code and storing them in separate files. However, for larger applications, this approach can be time consuming and complex. Use libraries to simplify the process and provide additional features that enhance application internationalization.
Disposing pluralization in i18n can be tricky because of different plural rules in different languages. However, many i18n libraries provide the ability to handle pluralization. For example, the i18n-js library provides a pluralize function that can handle plural forms according to the user's locale.
Testing the internationalization of the application involves checking whether the application correctly displays content and formats in different languages based on the user's locale. This can be done by manually changing locale settings in the browser or using automated testing tools. It is also important to check edge cases, such as lack of translation or incorrect plural forms.
Date and number formats may vary considerably between locales. Many i18n libraries provide the ability to format dates and numbers according to the user's locale. For example, the i18n-js library provides formatDate and formatNumber functions that can handle these tasks.
Handling right-to-left (RTL) languages in i18n involves adjusting the layout and text orientation of the application based on the user's locale. This can be done using CSS and HTML properties. Some i18n libraries also provide the functionality to handle RTL languages.
Localization, usually abbreviated as l10n, involves adapting your application to a specific locale, including translation content, formatting dates and numbers, and more. While i18n prepares your application to support multiple locales, l10n involves implementing these tweaks for each specific locale. Many i18n libraries also provide the functionality to handle localization.
The above is the detailed content of How to Implement Internationalization (i18n) in JavaScript. For more information, please follow other related articles on the PHP Chinese website!