Link Search Menu Expand Document

Messages class

Accessor class for compiled message functions generated by compileModule()

Signature:

export default class Messages 

Remarks

import Messages from '@messageformat/runtime/messages'

Example

// build.js
import { writeFileSync } from 'fs';
import MessageFormat from '@messageformat/core';

const mf = new MessageFormat(['en', 'fi']);
const msgSet = {
  en: {
    a: 'A {TYPE} example.',
    b: 'This has {COUNT, plural, one{one user} other{# users}}.',
    c: {
      d: 'We have {P, number, percent} code coverage.'
    }
  },
  fi: {
    b: 'Tällä on {COUNT, plural, one{yksi käyttäjä} other{# käyttäjää}}.',
    e: 'Minä puhun vain suomea.'
  }
};
writeFileSync('messages.js', String(mf.compile(msgSet)));

// runtime.js
import Messages from '@messageformat/runtime/messages';
import msgData from './messages';

const messages = new Messages(msgData, 'en');

messages.hasMessage('a')                // true
messages.hasObject('c')                 // true
messages.get('b', { COUNT: 3 })         // 'This has 3 users.'
messages.get(['c', 'd'], { P: 0.314 })  // 'We have 31% code coverage.'

messages.get('e')                       // 'e'
messages.setFallback('en', ['foo', 'fi'])
messages.get('e')                       // 'Minä puhun vain suomea.'

messages.locale = 'fi'
messages.hasMessage('a')                // false
messages.hasMessage('a', 'en')          // true
messages.hasMessage('a', null, true)    // true
messages.hasObject('c')                 // false
messages.get('b', { COUNT: 3 })         // 'Tällä on 3 käyttäjää.'
messages.get('c').d({ P: 0.628 })       // 'We have 63% code coverage.'

Constructors

Constructor Modifiers Description
(constructor)(msgData, defaultLocale)   Constructs a new instance of the Messages class

Properties

Property Modifiers Type Description
availableLocales   string[] Read-only list of available locales
defaultLocale   string | null Default fallback locale
locale   string | null Current locale

Methods

Method Modifiers Description
addMessages(data, locale, keypath)   Add new messages to the accessor; useful if loading data dynamically
get(key, props, locale)   Get the message or object corresponding to key
getFallback(locale)   Get the list of fallback locales
hasMessage(key, locale, fallback)   Check if key is a message function for the locale
hasObject(key, locale, fallback)   Check if key is a message object for the locale
resolveLocale(locale)   Resolve lc to the key of an available locale or null, allowing for partial matches.
setFallback(lc, fallback)   Set the fallback locale or locales for lc