around-the-world

2.0.0 • Public • Published

around-the-world

Travis Prettier npm semantic-release License

Simple to use ICU localization library built for MessageFormat

around-the-world is a utility library built for MessageFormat that makes it it simple to localize your app.

  • Lazily loads localization templates.
  • Simple API.
  • Dynamically change the locale.

Install

With yarn:

yarn add around-the-world

With npm:

npm install --save around-the-world

Usage

Loading From a Server

You can easily fetch string tables from your server using the loadLocale function and dynamic imports. The format is expected to be produced by the MessageFormat compiler.

const { localize } = await aroundTheWorld({
  loadLocale: locale => import(`/i18n/${locale}.js`),
});
 
localize('hello-world');

Compiling in the Client

You can compile ICU messages in the client directly with MessageFormat#compile.

import aroundTheWorld from 'around-the-world';
import MessageFormat from 'messageformat';
 
(async () => {
  const { localize } = await aroundTheWorld({
    loadLocale: locale => {
      if (locale === 'en-US') {
        const mf = new MessageFormat(locale);
        return mf.compile({
          hello_world: 'Hello, world!',
        });
      }
      throw new Error('Unknown locale!');
    },
  });
})();

Specifying Default Locale

You can specify the default locale to load using defaultLocale. If you don't supply this, navigator.language is used.

const { localize } = await aroundTheWorld({
  loadLocale: locale => {
    /* ... */
  },
 
  defaultLocale: 'en-AU',
});

Changing the Locale

You can read the current locale at any time by calling getCurrentLocale(), and you can set it by calling setCurrentLocale(). The latter returns a promise that resolves once the locale is loaded.

const { localize, getCurrentLocale, setCurrentLocale } = await aroundTheWorld({
  loadLocale: locale => {
    /* ... */
  },
});
 
getCurrentLocale(); // 'en-AU'
localize('hello'); // 'Hello'
 
await setCurrentLocale('jp');
localize('hello'); // 'こんにちは'

Readme

Keywords

none

Package Sidebar

Install

npm i around-the-world

Weekly Downloads

1

Version

2.0.0

License

MIT

Unpacked Size

7.57 kB

Total Files

4

Last publish

Collaborators

  • azz