compileModule() function

Compile a collection of messages into an ES module

Signature:

export default function compileModule(messageformat: MessageFormat<'string' | 'values'>, messages: StringStructure): string;

Parameters

Parameter Type Description
messageformat MessageFormat<‘string’ | ‘values’> A MessageFormat instance
messages StringStructure A hierarchical structure of ICU MessageFormat strings

Returns:

string

Remarks

Available as the default export of '@messageformat/core/compile-module', to allow for its exclusion from browser builds.

With messages as a hierarchical structure of ICU MessageFormat strings, the output of compileModule() will be the source code of an ES module with a default export matching the input structure, with each string replaced by its corresponding JS function. If the input includes anything other than simple variable replacements, the output ES module will have a dependency on '@messageformat/runtime'.

If the messageformat instance has been initialized with support for more than one locale, using a key that matches the locale’s identifier at any depth of a messages object will set its child elements to use that locale. To customize this behaviour, see MessageFormatOptions.localeCodeFromKey.

Example

import { writeFileSync } from 'fs'
import MessageFormat from '@messageformat/core'
import compileModule from '@messageformat/core/compile-module'

const mf = new MessageFormat('en')
const msgSet = {
  a: 'A {TYPE} example.',
  b: 'This has {COUNT, plural, one{one member} other{# members}}.',
  c: 'We have {P, number, percent} code coverage.'
}
const msgModule = compileModule(mf, msgSet)
writeFileSync('messages.js', msgModule)

...

import messages from './messages'

messages.a({ TYPE: 'more complex' })  // 'A more complex example.'
messages.b({ COUNT: 3 })              // 'This has 3 members.'