Utility FunctionsFormatting

formatMessage

スタンドアロンの formatMessage 関数に関するAPIリファレンス

概要

formatMessage メソッドは、変数の差し込みと locale に応じた書式設定でメッセージを整形します。 Format.JS の intl-messageformat ライブラリの上に構築されており、ICU message format のパターンをサポートします。

このメソッドは、変数の補間や複数形ルールの実装に不可欠です。 また、数値や日付の書式設定などにも対応しています。

import { formatMessage } from 'generaltranslation';

const formatted = formatMessage('こんにちは{name}さん、{count}件のメッセージがあります', {
  locales: ['en'],
  variables: { name: 'Alice', count: 5 }
});
// 戻り値: "こんにちはAliceさん、5件のメッセージがあります"

リファレンス

パラメーター

Prop

Type

options オブジェクト

プロパティ任意既定値説明
localesstring | string[]['en']フォーマットに使用する対応ロケール
variablesFormatVariables{}補間に使用する variables を含むオブジェクト

戻り値

string - 変数が展開され、locale 固有の書式設定が適用された整形済みメッセージ。


挙動

ロケールの処理

  • 指定された locales パラメーターで書式設定を行います
  • locales が指定されていない場合は ['en'] を既定値として使用します
  • 配列によるロケールのフォールバックチェーンをサポートします

Variable の処理

  • 単純置換: {variable} → value に置き換え
  • ICU message format: 複数形、select、各種フォーマットに完全対応
  • 変数が不足している場合: 出力では変更されず、そのまま残る

メッセージフォーマットのサポート

GT クラスのメソッドと同じ ICU message format の機能に対応:

  • 数値のフォーマット: {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(
  'You have {count, plural, =0 {no messages} =1 {one message} other {# messages}}',
  { count: 3 },
  'en'
);
console.log(notification); // "You have 3 messages"

通貨と数値のフォーマット

// ドイツ語ロケールの書式設定
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 {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 クラスのメソッドと同等の ICU message format 機能をサポート
  • 入力テンプレートが空の場合は空文字列を返します
  • variables は ICU の書式ルールより先に処理されます

次のステップ

このガイドはどうでしたか?

formatMessage