Utility FunctionsFormatting

formatMessage

独立函数 formatMessage 的 API 参考

概览

formatMessage 方法用于通过变量替换与符合 locale 的本地化格式来格式化消息。 它基于 Format.JS 的 intl-messageformat 库构建,支持 ICU 消息格式模式。

此方法对变量插值和复数处理(pluralization)至关重要。 它还支持数字与日期等格式化功能。

import { formatMessage } from 'generaltranslation';

const formatted = formatMessage('你好 {name},你有 {count} 条消息', {
  locales: ['en'],
  variables: { name: 'Alice', count: 5 }
});
// 返回:"你好 Alice,你有 5 条消息"

参考资料

参数

Prop

Type

Options 对象

属性类型可选默认值说明
localesstring | string[]['en']用于格式化的 locale(语言环境)
variablesFormatVariables{}含用于插值的变量的对象

返回

string - 已替换变量并应用特定 locale 格式的格式化消息。


行为表现

语言环境处理

  • 使用提供的 locales 参数进行格式化
  • 若未指定 locales,则回退至 ['en']
  • 通过数组支持 locale 回退链

变量处理

  • 简单替换:{variable} → 替换为 value
  • ICU 消息格式:完整支持复数、选择与格式化
  • 缺失的 variables:在输出中保持不变

消息格式支持

与 GT 类方法相同的 ICU 消息格式特性:

  • 数字格式化:{price, number, currency}
  • 日期格式化:{date, date, short}
  • 复数处理:{count, plural, ...}
  • 条件选择:{gender, select, ...}

示例

基本用法

import { formatMessage } from 'generaltranslation';

const greeting = formatMessage('你好 {name}!', {
  locales: ['en'],
  variables: { name: 'World' }
});
console.log(greeting); // "你好 World!"

无需 GT 实例

// 无需类实例化的格式化实用函数
function quickFormat(template: string, variables: any, locale = 'en') {
  return formatMessage(template, {
    locales: [locale],
    variables
  });
}

const notification = quickFormat(
  '您有 {count, plural, =0 {没有消息} =1 {一条消息} other {# 条消息}}',
  { count: 3 },
  'en'
);
console.log(notification); // "您有 3 条消息"

货币和数字格式化

// 德语区域格式化
const germanPrice = formatMessage('Preis: {price, number, currency}', {
  locales: ['de'],
  variables: { price: 1234.56 }
});
console.log(germanPrice); // "Preis: 1.234,56 €"

// 百分比格式化
const progress = formatMessage('Progress: {percent, number, percent}', {
  locales: ['en'],
  variables: { percent: 0.85 }
});
console.log(progress); // "Progress: 85%"

模板库

import { formatMessage } from 'generaltranslation';

class MessageTemplates {
  private locale: string;
  
  constructor(locale: string = 'en') {
    this.locale = locale;
  }
  
  welcome(name: string) {
    return formatMessage('欢迎回来,{name}!', {
      locales: [this.locale],
      variables: { name }
    });
  }
  
  itemCount(count: number) {
    return formatMessage(
      '{count, plural, =0 {没有项目} =1 {一个项目} other {# 个项目}}',
      {
        locales: [this.locale],
        variables: { count }
      }
    );
  }
}

const templates = new MessageTemplates('fr');
console.log(templates.welcome('Marie')); // "欢迎回来,Marie!"(法语)
console.log(templates.itemCount(5)); // "5 éléments"

注意事项

  • 需要在 options 中显式指定 locale
  • 支持与 GT class 方法相同的 ICU 消息格式功能
  • 对空输入模板返回空字符串
  • 在应用 ICU 消息格式规则之前先处理 variables

下一步

这份指南怎么样?

formatMessage