Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core message formatting functionality that processes ICU message strings with variable substitution, pluralization, date/time formatting, and number formatting.
Creates a new message formatter instance with locale and format configuration.
/**
* Creates a new IntlMessageFormat instance
* @param message - ICU message string or pre-parsed AST
* @param locales - Locale(s) for formatting (defaults to system locale)
* @param overrideFormats - Custom format configurations
* @param opts - Additional options including custom formatters
*/
constructor(
message: string | MessageFormatElement[],
locales?: string | string[],
overrideFormats?: Partial<Formats>,
opts?: Options
);Usage Examples:
import IntlMessageFormat from "intl-messageformat";
// Basic message
const simple = new IntlMessageFormat('Hello {name}!', 'en-US');
// Multiple locales with fallback
const multiLocale = new IntlMessageFormat(
'Hello {name}!',
['zh-CN', 'en-US']
);
// Custom number formats
const customFormat = new IntlMessageFormat(
'Price: {amount, number, currency}',
'en-US',
{
number: {
currency: { style: 'currency', currency: 'EUR' }
}
}
);
// Pre-parsed AST (for performance)
import { parse } from '@formatjs/icu-messageformat-parser';
const ast = parse('Hello {name}!');
const fromAst = new IntlMessageFormat(ast, 'en-US');Formats the message with provided values, returning the final formatted string or mixed array.
/**
* Format the message with provided values
* @param values - Object mapping placeholder names to values
* @returns Formatted string or mixed array for complex messages
*/
format<T = void>(
values?: Record<string, PrimitiveType | T | FormatXMLElementFn<T>>
): string | T | (string | T)[];Usage Examples:
// Simple variable substitution
const msg = new IntlMessageFormat('Hello {name}!', 'en-US');
msg.format({ name: 'Alice' }); // "Hello Alice!"
// Number formatting
const numMsg = new IntlMessageFormat(
'You have {count, number} items',
'en-US'
);
numMsg.format({ count: 1234 }); // "You have 1,234 items"
// Date formatting
const dateMsg = new IntlMessageFormat(
'Today is {today, date, long}',
'en-US'
);
dateMsg.format({ today: new Date() }); // "Today is January 15, 2024"
// Pluralization
const pluralMsg = new IntlMessageFormat(
'{count, plural, =0 {no items} one {# item} other {# items}}',
'en-US'
);
pluralMsg.format({ count: 0 }); // "no items"
pluralMsg.format({ count: 1 }); // "1 item"
pluralMsg.format({ count: 5 }); // "5 items"
// Select messages
const selectMsg = new IntlMessageFormat(
'{gender, select, male {He} female {She} other {They}} will respond shortly.',
'en-US'
);
selectMsg.format({ gender: 'female' }); // "She will respond shortly."
// XML/HTML tag formatting
const tagMsg = new IntlMessageFormat(
'Click <link>here</link> to continue.',
'en-US'
);
const result = tagMsg.format({
link: (chunks) => `<a href="/next">${chunks.join('')}</a>`
});
// Result: ['Click ', '<a href="/next">here</a>', ' to continue.']Formats the message and returns structured parts for advanced processing.
/**
* Format the message and return structured parts
* @param values - Object mapping placeholder names to values
* @returns Array of message parts with type information
*/
formatToParts<T>(
values?: Record<string, PrimitiveType | T | FormatXMLElementFn<T>>
): MessageFormatPart<T>[];Usage Examples:
const msg = new IntlMessageFormat('Hello {name}!', 'en-US');
const parts = msg.formatToParts({ name: 'Bob' });
// [
// { type: PART_TYPE.literal, value: 'Hello ' },
// { type: PART_TYPE.literal, value: 'Bob' },
// { type: PART_TYPE.literal, value: '!' }
// ]
// Complex message with objects
const complexMsg = new IntlMessageFormat(
'User: <user>{name}</user>',
'en-US'
);
const complexParts = complexMsg.formatToParts({
name: 'Alice',
user: (chunks) => ({ type: 'user', content: chunks.join('') })
});
// [
// { type: PART_TYPE.literal, value: 'User: ' },
// { type: PART_TYPE.object, value: { type: 'user', content: 'Alice' } }
// ]Returns the resolved locale and other options used by the formatter.
/**
* Get resolved options for this formatter
* @returns Object containing resolved locale
*/
resolvedOptions(): {
locale: string;
};Usage Examples:
const msg = new IntlMessageFormat('Hello!', ['zh-CN', 'en-US']);
const options = msg.resolvedOptions();
console.log(options.locale); // "zh-CN" (if supported) or "en-US"
// Check which locale was actually used
const detectedLocale = new IntlMessageFormat('Test', 'en-GB');
console.log(detectedLocale.resolvedOptions().locale); // "en-GB" or fallbackReturns the parsed Abstract Syntax Tree for the message.
/**
* Get the parsed AST for this message
* @returns Array of message format elements
*/
getAst(): MessageFormatElement[];Usage Examples:
const msg = new IntlMessageFormat('Hello {name}!', 'en-US');
const ast = msg.getAst();
// Returns parsed AST structure for advanced processingGets the default system locale.
/**
* Get the default system locale
* @returns Default locale string
*/
static get defaultLocale(): string;Resolves the best matching locale from provided options.
/**
* Resolve the best matching locale
* @param locales - Locale or array of locales to resolve
* @returns Resolved Intl.Locale object or undefined
*/
static resolveLocale(
locales: string | string[]
): Intl.Locale | undefined;Default format configurations that can be customized.
/**
* Default format configurations for number, date, and time formatting
*/
static formats: Formats;Usage Examples:
// Accessing default locale
console.log(IntlMessageFormat.defaultLocale); // "en-US" (example)
// Resolving locales
const resolved = IntlMessageFormat.resolveLocale(['es-MX', 'es', 'en']);
console.log(resolved?.toString()); // "es" or best match
// Customizing global formats (affects all new instances)
// Note: Better practice is to use custom formats per instance
const customFormats = {
number: { ...IntlMessageFormat.formats.number, currency: { style: 'currency', currency: 'EUR' } },
date: { ...IntlMessageFormat.formats.date, short: { year: '2-digit', month: 'short', day: 'numeric' } },
time: IntlMessageFormat.formats.time
};
// Apply custom formats to specific instances
const msg = new IntlMessageFormat('Price: {amount, number, currency}', 'en-US', customFormats);interface Options extends Omit<ParserOptions, 'locale'> {
formatters?: Formatters;
}
interface MessageFormatPart<T> {
type: PART_TYPE.literal | PART_TYPE.object;
value: string | T;
}
enum PART_TYPE {
literal = 0,
object = 1
}
type PrimitiveType = string | number | boolean | null | undefined | Date;
type FormatXMLElementFn<T, R = string | T | (string | T)[]> = (
parts: Array<string | T>
) => R;
// From @formatjs/icu-messageformat-parser
interface MessageFormatElement {
// AST element structure (imported from parser)
}
interface ParserOptions {
// Parser configuration options (imported from parser)
}