• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

globalizejs/globalize: A JavaScript library for internationalization and localiz ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

globalizejs/globalize

开源软件地址(OpenSource Url):

https://github.com/globalizejs/globalize

开源编程语言(OpenSource Language):

JavaScript 99.1%

开源软件介绍(OpenSource Introduction):

Globalize

Build Status devDependency Status devDependency Status

A JavaScript library for internationalization and localization that leverage the official Unicode CLDR JSON data. The library works both for the browser and as a Node.js module.

About Globalize

Why globalization?

Each language, and the countries that speak that language, have different expectations when it comes to how numbers (including currency and percentages) and dates should appear. Obviously, each language has different names for the days of the week and the months of the year. But they also have different expectations for the structure of dates, such as what order the day, month and year are in. In number formatting, not only does the character used to delineate number groupings and the decimal portion differ, but the placement of those characters differ as well.

A user using an application should be able to read and write dates and numbers in the format they are accustomed to. This library makes this possible, providing an API to convert user-entered number and date strings - in their own format - into actual numbers and dates, and conversely, to format numbers and dates into that string format.

Even if the application deals only with the English locale, it may still need globalization to format programming language bytes into human-understandable language and vice-versa in an effective and reasonable way. For example, to display something better than "Edited 1 minutes ago".

Why Globalize?

Globalize provides number formatting and parsing, date and time formatting and parsing, currency formatting, message formatting (ICU message format pattern), and plural support.

Design Goals.

  • Leverages the Unicode CLDR data and follows its UTS#35 specification.
  • Keeps code separate from i18n content. Doesn't host or embed any locale data in the library. Empowers developers to control the loading mechanism of their choice.
  • Allows developers to load as much or as little data as they need. Avoids duplicating data if using multiple i18n libraries that leverage CLDR.
  • Keeps code modular. Allows developers to load the i18n functionalities they need.
  • Runs in browsers and Node.js, consistently across all of them.
  • Makes globalization as easy to use as jQuery.

Globalize is based on the Unicode Consortium's Common Locale Data Repository (CLDR), the largest and most extensive standard repository of locale data available. CLDR is constantly updated and is used by many large applications and operating systems, so you'll always have access to the most accurate and up-to-date locale data.

Globalize needs CLDR content to function properly, although it doesn't embed, hard-code, or host such content. Instead, Globalize empowers developers to load CLDR data the way they want. Vanilla CLDR in its official JSON format (no pre-processing) is expected to be provided. As a consequence, (a) Globalize avoids bugs caused by outdated i18n content. Developers can use up-to-date CLDR data directly from Unicode as soon as it's released, without having to wait for any pipeline on our side. (b) Developers have full control over which locale coverage they want to provide on their applications. (c) Developers are able to share the same i18n dataset between Globalize and other libraries that leverage CLDR. There's no need for duplicating data.

Globalize is systematically tested against desktop and mobile browsers and Node.js. So, using it you'll get consistent results across different browsers and across browsers and the server.

Globalize doesn't use native Ecma-402 yet, which could potentially improve date and number formatting performance. Although Ecma-402 support is improving among modern browsers and even Node.js, the functionality and locale coverage level varies between different environments (see Comparing JavaScript Libraries slide 25). Globalize needs to do more research and testings to use it reliably.

For alternative libraries and more, check out this JavaScript globalization overview.

Migrating from Globalize 0.x

Are you coming from Globalize 0.x? Read our migration guide to learn what have changed and how to migrate older 0.x code to up-to-date 1.x.

Where to use it?

Globalize is designed to work both in the browser, or in Node.js. It supports both AMD and CommonJS.

Where does the data come from?

Globalize uses the Unicode CLDR, the largest and most extensive standard repository of locale data.

We do NOT embed any i18n data within our library. However, we make it really easy to use. Read How to get and load CLDR JSON data for more information on its usage.

Pick the modules you need

File Minified + gzipped size Runtime minified + gzipped size Summary
globalize.js 1.7KB 1.1KB Core library
globalize/currency.js 3.0KB 0.7KB Currency module provides currency formatting
globalize/date.js 7.7KB 4.3KB Date module provides date formatting and parsing
globalize/message.js 5.3KB 0.7KB Message module provides ICU message format support
globalize/number.js 4.4KB 2.6KB Number module provides number formatting and parsing
globalize/plural.js 2.3KB 0.4KB Plural module provides pluralization support
globalize/relative-time.js 0.8KB 0.5KB Relative time module provides relative time formatting support
globalize/unit.js 0.9KB 0.6KB Unit module provides unit formatting support

Browser Support

Globalize 1.x supports the following browsers:

  • Chrome: (Current - 1) or Current
  • Firefox: (Current - 1) or Current
  • Safari: 5.1+
  • Opera: 12.1x, (Current - 1) or Current
  • IE9+

(Current - 1) or Current denotes that we support the current stable version of the browser and the version that preceded it. For example, if the current version of a browser is 24.x, we support the 24.x and 23.x versions.

Getting Started

npm install globalize cldr-data iana-tz-data
var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );
Globalize.load( require( "cldr-data" ).entireMainFor( "en", "es" ) );
Globalize.loadTimeZone( require( "iana-tz-data" ) );

Globalize("en").formatDate(new Date());
// > "11/27/2015"

Globalize("es").formatDate(new Date());
// > "27/11/2015"

Note cldr-data is an optional module, read CLDR content section below for more information on how to get CLDR from different sources.

The iana-tz-data module is only needed when IANA time zones (via options.timeZone) are used with date functions. Read IANA time zone data below for more information.

Read the Locales section for more information about supported locales. For AMD, bower and other usage examples, see Examples section.

Installation

Downloading a ZIP or tarball archive

Click the GitHub releases tab and download the latest available Globalize package.

Using a package manager

You can use either npm or bower:

  • npm install globalize
  • bower install globalize

Building from source

  1. git clone https://github.com/globalizejs/globalize.git
  2. Build the distribution files

Requirements

1. Dependencies

If you use module loading like ES6 import, CommonJS, or AMD and fetch your code using package managers like npm or bower, you don't need to worry about this and can skip reading this section. Otherwise, you need to satisfy Globalize dependencies prior to using it. There is only one external dependency: cldr.js, which is a CLDR low level manipulation tool. Additionally, you need to satisfy the cross-dependencies between modules.

Module Dependencies (load in order)
Core module cldr.js
Currency module globalize.js (core), globalize/number.js, and globalize/plural.js (only required for "code" or "name" styles)
Date module globalize.js (core) and globalize/number.js
Message module globalize.js (core) and globalize/plural.js (if using messages that need pluralization support)
Number module globalize.js (core)
Plural globalize.js (core)
Relative time module globalize.js (core), globalize/number.js, and globalize/plural.js
Unit module globalize.js (core), globalize/number.js, and globalize/plural.js

As an alternative to deducing this yourself, use this online tool. The tool allows you to select the modules you're interested in using and tells you the Globalize files and CLDR JSON that you need.

2. CLDR content

Globalize is the i18n software (the engine). Unicode CLDR is the i18n content (the fuel). You need to feed Globalize on the appropriate portions of CLDR prior to using it.

(a) How do I figure out which CLDR portions are appropriate for my needs?

Each Globalize function requires a special set of CLDR portions. Once you know which Globalize functionalities you need, you can deduce its respective CLDR requirements. See table below.

Module Required CLDR JSON files
Core module cldr/supplemental/likelySubtags.json
Currency module cldr/main/locale/currencies.json
cldr/supplemental/currencyData.json
+CLDR JSON files from number module
+CLDR JSON files from plural module for name style support
Date module cldr/main/locale/ca-gregorian.json
cldr/main/locale/timeZoneNames.json
cldr/supplemental/metaZones.json
cldr/supplemental/timeData.json
cldr/supplemental/weekData.json
+CLDR JSON files from number module
Number module cldr/main/locale/numbers.json
cldr/supplemental/numberingSystems.json
Plural module cldr/supplemental/plurals.json (for cardinals)
cldr/supplemental/ordinals.json (for ordinals)
Relative time module cldr/main/locale/dateFields.json
+CLDR JSON files from number and plural modules
Unit module cldr/main/locale/units.json
+CLDR JSON files from number and plural module

As an alternative to deducing this yourself, use this online tool. The tool allows you to select the modules you're interested in using and tells you the Globalize files and CLDR JSON that you need.

(b) How am I supposed to get and load CLDR content?

Learn how to get and load CLDR content... and use Globalize.load() to load it.

3. IANA time zone data

The IANA time zone (tz) database, sometimes called the Olson database, is the standard data used by Unicode CLDR, ECMA-402, Linux, UNIX, Java, ICU, and others. It's used by Globalize to circumvent the JavaScript limitations with respect to manipulating date in time zones other than the user's environment.

In short, feed Globalize on IANA time zone data if you need to format or parse dates in a specific time zone, independently of the user's environment, e.g., America/Los_Angeles.

It's important to note there's no official IANA time zone data in the JSON format. Therefore, iana-tz-data has been adopted for convenience.

Learn more on Globalize.loadTimeZone().

Usage

Globalize's consumable-files are located in the ./dist directory. If you don't find it, it's because you are using a development branch. You should either use a tagged version or build the distribution files yourself. Read installation above if you need more information on how to download.

Globalize can be used for a variety of different i18n tasks, eg. formatting or parsing dates, formatting or parsing numbers, formatting messages, etc. You may NOT need Globalize in its entirety. For that reason, we made it modular. So, you can cherry-pick the pieces you need, eg. load dist/globalize.js to get Globalize core, load dist/globalize/date.js to extend Globalize with Date functionalities, etc.

An example is worth a thousand words. Check out our Examples section below.

Performance

When formatting or parsing, there's actually a two-step process: (a) the formatter (or parser) creation and (b) its execution, where creation takes an order of magnitude more time (more expensive) than execution. In the creation phase, Globalize traverses the CLDR tree, processes data (e.g., expands date patterns, parses plural rules, etc), and returns a function that actually executes the formatting or parsing.

// Formatter creation.
var formatter = Globalize.numberFormatter();

// Formatter execution (roughly 10x faster than above).
formatter( Math.PI );
// > 3.141

As a rule of thumb for optimal performance, cache your formatters and parsers. For example: (a) on iterations, generate them outside the loop and reuse while looping; (b) on server applications, generate them in advance and execute when requests arrive.

Compilation and the Runtime modules

Take advantage of compiling your formatters and/or parsers during build time when deploying to production. It's much faster than generating them in real-time and it's also much smaller (i.e., better loading performance).

Your compiled formatters and parsers allow you to skip a big part of the library and also allow you to skip loading CLDR data, because they have already been created (see Performance above for more information).

To illustrate, see our Basic Globalize Compiler example.

Globalize Compiler

For information about the Globalize Compiler CLI or its JavaScript API, see the Globalize Compiler documentation.

Examples

The fastest and easiest way to use Globalize is by integrating it into your existing tools.

If you're using a different tool than the one above, but you're comfortable using JavaScript modules (such as ES6 modules, CommonJS, or AMD) and package managers like npm or bower, you may want to check out the following examples. Note you'll need to compile your code for production yourself.

If you're using none of the tools above, but instead you're using the plain and old script tags only, the following example may interest you. Note Globalize allows you to go low level like this. But, acknowledge that you'll need to handle dependencies and CLDR loading manually yourself.

Community

You can find us on Slack. If you're new, join here.

API

Core module

Globalize.load( cldrJSONData, ... )

This method allows you to load CLDR JSON locale data. Globalize.load() is a proxy to Cldr.load(). Read more...

Globalize.locale( [locale|cldr] )

Set default locale, or get it if locale argument is omitted. Read more...

[new] Globalize( locale|cldr )

Create a Globalize instance. Read more...

Locales

A locale is an identifier (id) that refers to a set of user preferences that tend to be shared across significant swaths of the world. In technical terms, it's a String composed of three parts: language, script, and region. For example:

locale description
en-Latn-US English as spoken in the Unites States in the Latin script.
en-US English as spoken in the Unites States (Latin script is deduced given it's the most likely script used in this place).
en English (United States region and Latin script are deduced given they are respectively the most likely region and script used in this place).
en-GB English as spoken in the United Kingdom (Latin script is deduced given it's the most likely script used in this place).
en-IN English as spoken in India (Latin script is deduced).
es Spanish (Spain region and Latin script are deduced).
es-MX Spanish as spoken in Mexico (Latin script is deduced).
zh Chinese (China region and Simplified Han script are deduced).
zh-TW Chinese as spoken in Taiwan (Traditional Han script is deduced).
ja Japanese (Japan region and Japanese script are deduced).
de German (Germany region and Latin script are deduced).
pt Portuguese (Brazil region and Latin script are deduced).
pt-PT Portuguese as spoken in Portugal (Latin script is deduced).
fr French (France region and Latin script are deduced).
ru Russian (Russia region and Cyrillic script are deduced).
ar Arabic (Egypt region and Arabic script are deduced).

The likely deductibility is computed by using CLDR data, which is based on the population and the suppress-script data in BCP47 (among others). The data is heuristically derived, and may change over time.

Figure out the deduced information by looking at the cldr.attributes.maxLanguageId property of a Globalize instance:

var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );
Globalize( "en" ).cldr.attributes.maxLanguageId;
// > "en-Latn-US"

Globalize supports all the locales available in CLDR, which are around 740. For more information, search for coverage charts at the downloads section of http://cldr.unicode.org/.

Read more details about locale at UTS#35 locale.

Date module

Globalize.loadTimeZone( ianaTzData )

This method allows you to load IANA time zone data to enable options.timeZone feature on date formatters and parsers.

Read more...

.dateFormatter( [options] )

Return a function that formats a date according to the given options. The default formatting is numeric year, month, and day (i.e., { skeleton: "yMd" }.

.dateFormatter()( new Date() )
// > "11/30/2010"

.dateFormatter({ skeleton: "GyMMMd" })( new Date() )
// > "Nov 30, 2010 AD"

.dateFormatter({ date: "medium" })( new Date() )
// > "Nov 1, 2010"

.dateFormatter({ time: "medium" })( new Date() )
// > "5:55:00 PM"

.dateFormatter({ datetime: "medium" })( new Date() )
// > "Nov 1, 2010, 5:55:00 PM"

.dateFormatter({ datetime: "full", timeZone: "America/New_York" })( new Date() );
// > "Monday, November 1, 2010 at 3:55:00 AM Eastern Daylight Time"

.dateFormatter({ datetime: "full", timeZone: "America/Los_Angeles" })( new Date() );
// > "Monday, November 1, 2010 at 12:55:00 AM Pacific Daylight Time"

Read more...

.dateToPartsFormatter( [options] )

Return a function that formats a date into parts tokens according to the given options. The default formatting is numeric year, month, and day (i.e., { skeleton: "yMd" }.

.dateToPartsFormatter()( new Date() )
// > [
//   { "type": "month", "value": "3" },
//   { "type": "literal", "value": "/" },
//   { "type": "day", "value": "17" },
//   { "type": "literal", "value": "/" },
//   { "type": "year", "value": "2017" }
// ]

Read more...

.dateParser( [options] )

Return a function that parses a string representing a date into a JavaScript Date object according to the given options. The default parsing assumes numeric year, month, and day (i.e., { skeleton: "yMd" }).

.dateParser()( "11/30/2010" )
// > new Date( 2010, 10, 30, 0, 0, 0 )

.dateParser({ skeleton: "GyMMMd" })( "Nov 30, 2010 AD" )
// > new Date( 2010, 10, 30, 0, 0, 0 )

.dateParser({ date: "medium" })( "Nov 1, 2010" )
// > new Date( 2010, 10, 30, 0, 0, 0 )

.dateParser({ time: "medium" })( "5:55:00 PM" )
// > new Date( 2015, 3, 22, 17, 55, 0 ) // i.e., today @ 5:55PM

.dateParser({ datetime: "medium" })( "Nov 1, 2010, 5:55:00 PM" )
// > new Date( 2010, 10, 30, 17, 55, 0 )

Read more...

.formatDate( value [, options] )

Alias for .dateFormatter( [options] )( value ).


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap