10.5.11 • Published 3 months ago

intl-messageformat v10.5.11

Weekly downloads
1,471,437
License
BSD-3-Clause
Repository
github
Last release
3 months ago

Intl MessageFormat

Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.

npm Version

`intl-messageformat` minzipped size `intl-messageformat/core` minzipped size

Overview

Goals

This package aims to provide a way for you to manage and format your JavaScript app's string messages into localized strings for people using your app. You can use this package in the browser and on the server via Node.js.

This implementation is based on the Strawman proposal, but there are a few places this implementation diverges.

Note: This IntlMessageFormat API may change to stay in sync with ECMA-402, but this package will follow semver.

How It Works

Messages are provided into the constructor as a String message, or a pre-parsed AST object.

const msg = new IntlMessageFormat(message, locales, [formats], [opts]);

The string message is parsed, then stored internally in a compiled form that is optimized for the format() method to produce the formatted string for displaying to the user.

const output = msg.format(values);

Common Usage Example

A very common example is formatting messages that have numbers with plural labels. With this package you can make sure that the string is properly formatted for a person's locale, e.g.:

const MESSAGES = {
  'en-US': {
    NUM_PHOTOS:
      'You have {numPhotos, plural, ' +
      '=0 {no photos.}' +
      '=1 {one photo.}' +
      'other {# photos.}}',
  },

  'es-MX': {
    NUM_PHOTOS:
      'Usted {numPhotos, plural, ' +
      '=0 {no tiene fotos.}' +
      '=1 {tiene una foto.}' +
      'other {tiene # fotos.}}',
  },
};

const output;

const enNumPhotos = new IntlMessageFormat(
  MESSAGES['en-US'].NUM_PHOTOS,
  'en-US'
);
output = enNumPhotos.format({numPhotos: 1000});
console.log(output); // => "You have 1,000 photos."

const esNumPhotos = new IntlMessageFormat(
  MESSAGES['es-MX'].NUM_PHOTOS,
  'es-MX'
);
output = esNumPhotos.format({numPhotos: 1000});
console.log(output); // => "Usted tiene 1,000 fotos."

Message Syntax

The message syntax that this package uses is not proprietary, in fact it's a common standard message syntax that works across programming languages and one that professional translators are familiar with. This package uses the ICU Message syntax and works for all CLDR languages which have pluralization rules defined.

Features

  • Uses industry standards: ICU Message syntax and CLDR locale data.

  • Supports plural, select, and selectordinal message arguments.

  • Formats numbers and dates/times in messages using Intl.NumberFormat and Intl.DateTimeFormat, respectively.

  • Optimized for repeated calls to an IntlMessageFormat instance's format() method.

  • Supports defining custom format styles/options.

  • Supports escape sequences for message syntax chars, e.g.: "'{foo}'" will output: "{foo}" in the formatted output instead of interpreting it as a foo argument.

Usage

Modern Intl Dependency

This package assumes that the Intl global object exists in the runtime. Intl is present in all modern browsers (IE11+) and Node (with full ICU). The Intl methods we rely on are:

  1. Intl.NumberFormat for number formatting (can be polyfilled using Intl.js)
  2. Intl.DateTimeFormat for date time formatting (can be polyfilled using Intl.js)
  3. Intl.PluralRules for plural/ordinal formatting (can be polyfilled using @formatjs/intl-pluralrules)

Loading Intl MessageFormat in a browser

<script src="intl-messageformat/intl-messageformat.min.js"></script>

Loading Intl MessageFormat in Node.js

Either do:

import IntlMessageFormat from 'intl-messageformat';
const IntlMessageFormat = require('intl-messageformat').default;

NOTE: Your Node has to include full ICU

Public API

IntlMessageFormat Constructor

To create a message to format, use the IntlMessageFormat constructor. The constructor takes three parameters:

  • message - {String | AST} - String message (or pre-parsed AST) that serves as formatting pattern.

  • locales - {String | String[]} - A string with a BCP 47 language tag, or an array of such strings. If you do not provide a locale, the default locale will be used. When an array of locales is provided, each item and its ancestor locales are checked and the first one with registered locale data is returned. See: Locale Resolution for more details.

  • formats - {Object} - Optional object with user defined options for format styles.

  • opts - { formatters?: Formatters }: Optional options.

    • formatters: Map containing memoized formatters for performance.
const msg = new IntlMessageFormat('My name is {name}.', 'en-US');

Locale Resolution

IntlMessageFormat uses Intl.NumberFormat.supportedLocalesOf() to determine which locale data to use based on the locales value passed to the constructor. The result of this resolution process can be determined by call the resolvedOptions() prototype method.

resolvedOptions() Method

This method returns an object with the options values that were resolved during instance creation. It currently only contains a locale property; here's an example:

const msg = new IntlMessageFormat('', 'en-us');
console.log(msg.resolvedOptions().locale); // => "en-US"

Notice how the specified locale was the all lower-case value: "en-us", but it was resolved and normalized to: "en-US".

format(values) Method

Once the message is created, formatting the message is done by calling the format() method on the instance and passing a collection of values:

const output = msg.format({name: 'Eric'});
console.log(output); // => "My name is Eric."

Note: A value must be supplied for every argument in the message pattern the instance was constructed with.

getAst Method

Return the underlying AST for the compiled message

formatHTMLMessage method

Formats message containing HTML tags & can be used to embed rich text formatters such as React. For example:

const mf = new IntlMessageFormat('hello <b>world</b>', 'en');
mf.formatHTMLMessage({b: str => <span>{str}</span>});
// returns ['hello ', React element rendered as <span>world</span>]

Caveats

This is not meant to be a full-fledged method to embed HTML, but rather to tag specific text chunk so translation can be more contextual. Therefore, the following restrictions apply:

  1. Any attributes on the HTML tag are also ignored.
  2. Self-closing tags are not supported, please use regular ICU placeholder like {placeholder}.
  3. HTML tags must be all lowercased since it's case-insensitive.
  4. Self-closing tags can not be used as HTML tag placeholder. For e.g. "Please click this <link>link</link>" will not work because <link/> is a self-closing tag, and it can not be parsed correctly by browser DOMParser.
  • List of self-closing tags is defined here.

If you don't have DOMParser available in your environment (e.g. Node.js), you need to add a polyfill. One of the packages that provides such a polyfill is jsdom.

User Defined Formats

Define custom format styles is useful you need supply a set of options to the underlying formatter; e.g., outputting a number in USD:

const msg = new IntlMessageFormat(
  'The price is: {price, number, USD}',
  'en-US',
  {
    number: {
      USD: {
        style: 'currency',
        currency: 'USD',
      },
    },
  }
);

const output = msg.format({price: 100});
console.log(output); // => "The price is: $100.00"

In this example, we're defining a USD number format style which is passed to the underlying Intl.NumberFormat instance as its options.

Advanced Usage

Passing in AST

You can pass in pre-parsed AST to IntlMessageFormat like this:

import IntlMessageFormat from 'intl-messageformat';
new IntlMessageFormat('hello').format(); // prints out hello

// is equivalent to

import IntlMessageFormat from 'intl-messageformat/core';
import parser from 'intl-messageformat-parser';
new IntlMessageFormat(parser.parse('hello')).format(); // prints out hello

This helps performance for cases like SSR or preload/precompilation-supported platforms since AST can be cached.

If your messages are all in ASTs, you can alias intl-messageformat-parser to {default: undefined} to save some bytes during bundling.

Formatters

For complex messages, initializing Intl.* constructors can be expensive. Therefore, we allow user to pass in formatters to provide memoized instances of these Intl objects. This opts combines with passing in AST and intl-format-cache can speed things up by 30x per the benchmark down below.

For example:

import IntlMessageFormat from 'intl-messageformat';
import memoizeIntlConstructor from 'intl-format-cache';
const formatters = {
  getNumberFormat: memoizeIntlConstructor(Intl.NumberFormat),
  getDateTimeFormat: memoizeIntlConstructor(Intl.DateTimeFormat),
  getPluralRules: memoizeIntlConstructor(Intl.PluralRules),
};
new IntlMessageFormat('hello {number, number}', 'en', undefined, {
  formatters,
}).format({number: 3}); // prints out `hello, 3`

Examples

Plural Label

This example shows how to use the ICU Message syntax to define a message that has a plural label; e.g., "You have 10 photos":

You have {numPhotos, plural,
    =0 {no photos.}
    =1 {one photo.}
    other {# photos.}
}
const MESSAGES = {
    photos: '...', // String from code block above.
    ...
};

const msg = new IntlMessageFormat(MESSAGES.photos, 'en-US');

console.log(msg.format({numPhotos: 0}));    // => "You have no photos."
console.log(msg.format({numPhotos: 1}));    // => "You have one photo."
console.log(msg.format({numPhotos: 1000})); // => "You have 1,000 photos."

Note: how when numPhotos was 1000, the number is formatted with the correct thousands separator.

Benchmark

format_cached_complex_msg x 539,674 ops/sec ±1.87% (87 runs sampled)
format_cached_string_msg x 99,311,640 ops/sec ±2.15% (87 runs sampled)
new_complex_msg_preparsed x 1,490 ops/sec ±8.37% (54 runs sampled)
new_complex_msg x 836 ops/sec ±31.96% (67 runs sampled)
new_string_msg x 27,752 ops/sec ±8.25% (65 runs sampled)
complex msg format x 799 ops/sec ±9.38% (55 runs sampled)
complex msg w/ formatters format x 1,878 ops/sec ±16.63% (64 runs sampled)
complex preparsed msg w/ formatters format x 26,482 ops/sec ±2.55% (84 runs sampled)

License

This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.

@goocan/lowcode-vue-renderer@invoice-simple/react-intlmiot-workspace@everreal/er-common-translations@platform-foxtrot/intlintl-i18nuser-management-uilighthouse-plugin-publisher-ads-alphaignoreyuki-t@bayerischer-rundfunk/react-intluplandjsreact-intl-rev@picker-cc/core@infinitebrahmanuniverse/nolb-intl@samsquatch/alteryx-components@samsquatch/components-starter@samsquatch/jobber-components@samsquatch/mom-components-starter@samsquatch/traction-tools-components@samsquatch/trustedhealth-components@samsquatch/vanilla-components-disney@samsquatch/vanilla-components-fragment@samsquatch/vanilla-components-global@samsquatch/vanilla-components-meta@cdlab996/knxcloud-lowcode-vue-rendererlighthouse@everything-registry/sub-chunk-1922vporelrev_demo@appsemble/utils@appsemble/node-utils@ant-design/pro-cli@anticrm/platform@awsui/components-react@axa-ch/pod-eliah-vorsorgeportal@4c/react-intlai18n-client@alicloud/console-components-intl@alicloud/console-components-intl-core@adonisjs/i18n@adonisjs/antl@alita/pro-cli@abpx/lowcode-vue-renderer@aligov/global-string-formatalaskaalaska-admin-view@aligov/i18n-utilalp-translatealp-node@alilc/lowcode-editor-core@aliwind/rc-intlalilc-lowcode-editor-corealilc-lowcode-renderer-core@wix/bex-utils@watson-virtual-agent/chat-widgetadonis-antladonis-antl-improving7ghost@asiz33/smartblok-vendure-plugin@avasdk/utils-i18n@attachments/i18naudit-tool@bazo/js-translator@boomfly/svelte-i18nbanana-corebanyancloud_ui_test@braw/vue-intl-controller@byted-apaas/i18n@ceed/ads@cc-dev-kit-test/console-components-intl@cdlab996/lowcode-vue-renderer2.7@bankify/react-intl-universal@binarygiant/i18n-demo@canva/app-ui-kit@brightspace-ui/core@brightspace-ui/localize-behaviorbrainfock@compeon-os/translated-components@compeon/translated-components@contember/react-i18n@cloudscape-design/componentsbox-ui-elements-mlh@codebet/react-intlboxtadecudos-js-sdkcuvp-packagescuvp-renderer-corecustom-card-helpersdi18n-reactnshakhat_ghostnuke-intlnunjucks-intlodioexcepturiopenblocks-coreonix-coreconsequatursit@digiforce-cloud/dvd-renderer-core@dermotduffy/custom-card-helpers@digiforce-cloud/dvd-editor-coremorganatwork-ghost
10.5.11

3 months ago

10.5.10

3 months ago

10.5.9

3 months ago

10.5.5

5 months ago

10.5.6

5 months ago

10.5.7

5 months ago

10.5.8

5 months ago

10.5.4

6 months ago

10.5.2

7 months ago

10.5.3

7 months ago

10.5.1

7 months ago

10.4.0

11 months ago

10.5.0

10 months ago

10.3.4

1 year ago

10.3.5

12 months ago

10.3.2

1 year ago

10.3.3

1 year ago

10.3.1

1 year ago

10.2.6

1 year ago

10.3.0

1 year ago

10.2.4

1 year ago

10.2.5

1 year ago

10.2.0

2 years ago

10.2.1

2 years ago

10.2.2

1 year ago

10.1.4

2 years ago

10.1.5

2 years ago

10.1.2

2 years ago

10.1.3

2 years ago

10.0.1

2 years ago

10.1.0

2 years ago

10.1.1

2 years ago

9.13.0

2 years ago

9.12.0

2 years ago

9.11.1

2 years ago

9.11.2

2 years ago

9.11.3

2 years ago

9.11.4

2 years ago

9.11.0

2 years ago

9.10.0

2 years ago

9.9.6

2 years ago

9.9.5

2 years ago

9.9.4

2 years ago

9.9.3

3 years ago

9.9.2

3 years ago

9.9.1

3 years ago

9.9.0

3 years ago

9.8.2

3 years ago

9.8.1

3 years ago

9.8.0

3 years ago

9.7.1

3 years ago

9.7.0

3 years ago

9.6.17

3 years ago

9.6.18

3 years ago

9.6.16

3 years ago

9.6.14

3 years ago

9.6.15

3 years ago

9.6.12

3 years ago

9.6.13

3 years ago

9.6.10

3 years ago

9.6.11

3 years ago

9.6.9

3 years ago

9.6.8

3 years ago

9.6.7

3 years ago

9.6.6

3 years ago

9.6.5

3 years ago

9.6.4

3 years ago

9.6.3

3 years ago

9.6.2

3 years ago

9.6.1

3 years ago

9.5.4

3 years ago

9.6.0

3 years ago

9.5.3

3 years ago

9.5.2

3 years ago

9.5.1

3 years ago

9.5.0

3 years ago

9.4.9

3 years ago

9.4.8

3 years ago

9.4.7

3 years ago

9.4.6

3 years ago

9.4.5

3 years ago

9.4.4

3 years ago

9.4.3

3 years ago

9.4.2

3 years ago

9.4.1

3 years ago

9.4.0

3 years ago

9.3.20

3 years ago

9.3.19

3 years ago

9.3.18

3 years ago

9.3.17

3 years ago

9.3.16

3 years ago

9.3.14

3 years ago

9.3.15

3 years ago

9.3.13

3 years ago

9.3.12

3 years ago

9.3.11

4 years ago

9.3.10

4 years ago

9.3.9

4 years ago

9.3.8

4 years ago

9.3.7

4 years ago

9.3.6

4 years ago

9.3.5

4 years ago

9.3.4

4 years ago

9.3.3

4 years ago

9.3.2

4 years ago

9.3.1

4 years ago

9.3.0

4 years ago

9.2.5

4 years ago

9.2.4

4 years ago

9.2.3

4 years ago

9.2.2

4 years ago

9.2.1

4 years ago

9.2.0

4 years ago

9.1.7

4 years ago

9.1.6

4 years ago

9.1.5

4 years ago

9.1.4

4 years ago

9.1.3

4 years ago

9.1.2

4 years ago

9.1.1

4 years ago

9.1.0

4 years ago

9.0.4-alpha.0

4 years ago

9.0.2

4 years ago

9.0.1

4 years ago

9.0.0

4 years ago

8.4.1

4 years ago

8.4.0

4 years ago

8.3.26

4 years ago

8.3.25

4 years ago

8.3.24

4 years ago

8.3.23

4 years ago

8.3.21

4 years ago

8.3.20

4 years ago

8.3.19

4 years ago

8.3.18

4 years ago

8.3.17

4 years ago

8.3.16

4 years ago

8.3.14

4 years ago

8.3.15

4 years ago

8.3.12

4 years ago

8.3.13

4 years ago

8.3.11

4 years ago

8.3.10

4 years ago

8.3.9

4 years ago

8.3.8

4 years ago

8.3.7

4 years ago

8.3.6

4 years ago

8.3.5

4 years ago

8.3.4

4 years ago

8.3.2

4 years ago

8.3.1

4 years ago

8.2.3

4 years ago

8.2.2

4 years ago

8.2.1

4 years ago

8.1.0

4 years ago

8.2.0

4 years ago

8.0.0

4 years ago

7.8.4

4 years ago

7.8.3

4 years ago

7.8.2

4 years ago

7.8.1

4 years ago

7.8.0

4 years ago

7.7.5

4 years ago

7.7.4

4 years ago

7.7.3

4 years ago

7.7.2

4 years ago

7.7.1

4 years ago

7.6.2

4 years ago

7.7.0

4 years ago

7.6.1

4 years ago

7.6.0

4 years ago

7.5.6

4 years ago

7.5.5

4 years ago

7.5.4

4 years ago

7.5.4-alpha.7

4 years ago

7.5.4-alpha.6

4 years ago

7.5.3

4 years ago

7.5.2

4 years ago

7.5.1

4 years ago

7.5.0

4 years ago

7.3.3

4 years ago

7.3.2

5 years ago

7.3.1

5 years ago

7.3.0

5 years ago

7.2.4

5 years ago

7.2.3

5 years ago

7.2.2

5 years ago

7.2.1

5 years ago

7.2.0

5 years ago

7.1.6

5 years ago

7.1.5

5 years ago

7.1.4

5 years ago

7.1.3

5 years ago

7.1.2

5 years ago

7.1.1

5 years ago

7.1.0

5 years ago

7.0.0

5 years ago

6.1.11

5 years ago

6.1.10

5 years ago

6.1.9

5 years ago

6.1.7

5 years ago

6.1.6

5 years ago

6.1.5

5 years ago

6.1.4

5 years ago

6.1.3

5 years ago

6.1.2

5 years ago

6.1.1

5 years ago

6.1.0

5 years ago

6.0.4

5 years ago

6.0.3

5 years ago

6.0.2

5 years ago

6.0.1

5 years ago

6.0.0

5 years ago

5.4.3

5 years ago

5.4.2

5 years ago

5.4.1

5 years ago

5.4.0

5 years ago

5.3.0

5 years ago

5.2.0

5 years ago

5.1.2

5 years ago

5.1.0

5 years ago

5.0.1

5 years ago

5.0.0

5 years ago

4.4.0

5 years ago

4.3.0

5 years ago

4.2.1

5 years ago

4.1.2

5 years ago

4.1.1

5 years ago

4.1.0

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.3.0

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.0

5 years ago

2.2.0

6 years ago

2.1.0

7 years ago

2.0.0

7 years ago

1.3.0

8 years ago

1.2.0

8 years ago

1.1.0

9 years ago

1.0.4

9 years ago

1.0.3

9 years ago

1.0.2

9 years ago

1.0.1

10 years ago

1.0.0

10 years ago

1.0.0-rc-6

10 years ago

1.0.0-rc-5

10 years ago

1.0.0-rc-4

10 years ago

1.0.0-rc-3

10 years ago

1.0.0-rc-2

10 years ago

1.0.0-rc-1

10 years ago

0.1.0

10 years ago

0.1.0-rc-3

10 years ago

0.1.0-rc-2

10 years ago

0.1.0-rc-1

10 years ago

0.0.1

10 years ago