For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/stage/unstaged/proposal-intl-message-resource.md.
  • 简体中文
  • Intl.MessageResource ?

    提案概览
    提案速览

    该提案扩展了 Intl.MessageFormat 提案,通过添加静态 parseResource() 方法来一次性解析整个消息资源(捆绑包),而不仅仅是单个消息。它引入了 MessageResource 类型,作为 MessageFormat 实例的 Map,支持扁平或层次化的消息组织。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    Intl.MessageFormat.parseResource()

    这是 Intl.MessageFormat 提案 的后续提案, 除了支持单个消息外,还增加了对处理整个消息资源(即捆绑包)的支持。

    状态

    champions: Eemeli Aro (Mozilla/OpenJS Foundation)

    阶段:1

    动机和使用场景

    在大多数使用场景中,需要格式化消息的系统通常需要格式化不止一条消息。 例如,一个对话框可能包含标题、描述和一个或多个带有标签的按钮。 这些消息需要作为一个整体单元来处理, 无论是编辑、翻译还是格式化时。

    为了实现这一点,消息资源语法正在与 MessageFormat 2.0 规范并行开发。 本提案添加了一个静态方法 Intl.MessageFormat.parseResource(),用于解析此类资源。 这样的方法将允许 MF2 消息存储在专门构建的容器中并进行传输, 而不需要在 JavaScript 环境中单独解析。

    API 描述

    作为基线,本提案假定 Intl.MessageFormat 存在,如其提案中所述, 并对其进行扩展。

    MessageFormat.parseResource(resource, locales?, options?)

    此静态方法解析 MF2 资源的字符串表示, 构建一个 Map,其中包含与资源的每条消息对应的 MessageFormat 实例结构。 其 localesoptions 参数用于构造每个这样的实例。

    MessageResource 是一个 Map,表示单个语言环境的一组相关消息。 消息可以组织为扁平结构,也可以使用路径组织为层次结构。 从概念上讲,它类似于包含一组消息的文件, 但对底层实现没有施加限制。

    type MessageResource = Map<string, Intl.MessageFormat | MessageResource>;
    
    class Intl.MessageFormat {
      static parseResource(
        resource: string,
        locales?: string | string[],
        options?: MessageFormatOptions
      ): MessageResource;
    
      ...
    }

    示例

    给定一个如下所示的 MF2 资源:

    # 注意!MF2 语法正在开发中;这可能会改变
    
    greeting = {Hello {$place}!}
    
    new_notifications =
      match {$count}
      when 0   {You have no new notifications}
      when one {You have {$count} new notification}
      when *   {You have {$count} new notifications}

    可以在代码中这样使用:

    const source = ... // 如上所述的资源的字符串源
    const res = Intl.MessageFormat.parseResource(source, ['en']);
    
    const greeting = res.get('greeting').resolveMessage({ place: 'world' });
    greeting.toString(); // 'Hello world!'
    
    const notifications = res.get('new_notifications').resolveMessage({ count: 1 });
    notifications.toString(); // 'You have 1 new notification'