ICU 訊息格式

本頁示範在 Intor 中整合 ICU Message Format 的最小實作方式。


Intor 並未內建 ICU 語法。
ICU 為選用功能,可在需要時自行整合。

格式化的責任則交由成熟且符合標準的工具處理。

在此範例中,我們使用 intl-messageformat 作為 ICU 格式化引擎。

詳見:FormatJS


安裝

安裝 intl-messageformat:

npm install intl-messageformat
yarn add intl-messageformat
pnpm add intl-messageformat
bun add intl-messageformat

整合步驟

♯1 Format Handler

由於 Intor 已內建處理 interpolationrich tags,使用 IntlMessageFormat 時需關閉其 tag 解析。

以下示範一個基本的 ICU Format Handler 實作:

import type { FormatHandler, MessageValue } from "intor";
import IntlMessageFormat from "intl-messageformat";

export const icuFormatHandler: FormatHandler = ({
  rawMessage,
  locale,
  replacements,
}) => {
  const formatter = new IntlMessageFormat(
    rawMessage,
    locale,
    {},
    { ignoreTag: true },
  );
  return formatter.format(replacements) as MessageValue;
};

♯2 注入 Handler

icuFormatHandler 於初始化時注入至 handlers
關於注入方式,詳見:Handlers & Hooks


使用範例

以下示範一個使用 ICU Message Format 的翻譯範例:

export const intorConfig = defineIntorConfig({
  defaultLocale: "en",
  supportedLocales: ["en", "fr"],
  messages: {
    en: { icu: "Price: {value, number, ::currency/USD}" },
    fr: { icu: "Price: {value, number, ::currency/EUR}" },
  },
});

// ...

<p>{t("icu", { value: 12.5 })}</p>
// en → Price: $12.50
// fr → Price: 12,50 €

詳見:ICU Message syntax