# @asyncapi/optimizer 中文文档

规范地址：https://npmcn.com/package/%40asyncapi/optimizer/

版本：2\.0\.1
npm 元数据更新时间：2026-11-02T08:25:07.767Z
中文译文更新时间：2026-11-07T01:38:07.426Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40asyncapi/optimizer
原文对照：https://npmcn.com/package/%40asyncapi/optimizer/?lang=original
项目主页：https://github.com/asyncapi/cli/tree/master/packages/optimizer#readme
源码仓库：https://github.com/asyncapi/cli

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：85.3 kB，39 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：6 个
- peer 依赖：@asyncapi/parser ^3\.6\.0
- 首次发布：2021-08-10T13:36:37.447Z
- 最新版本发布：2026-11-02T08:25:07.346Z
- 近 30 天下载量：293339（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：56（近 12 个月 4 个）

## 中文简介

此库将优化 AsyncAPI 规格文件 .

## 安装

```sh
npm install @asyncapi/optimizer
```

也可以使用：`pnpm add @asyncapi/optimizer`、`yarn add @asyncapi/optimizer`、`bun add @asyncapi/optimizer`

## README

[![AsyncAPI Optimizer](https://npmcn.com/package/%40asyncapi/optimizer/assets/readme-banner.png)](https://www.asyncapi.com/)

AsyncAPI提供了许多方式来再利用文档的某些部分,如消息或计划定义或外部文件的引用,更不用提特征了. 宗旨 **AsyncAPI 优化器** 使 AsyncAPI 文件实现优化。 它是一个可以用于UI和CLI的库.

> **这个包裹现在生活在 [`asyncapi/cli`](https://github.com/asyncapi/cli) 单相** 下级 `packages/optimizer/` 从那里释放(同一个 npm 名称) `@asyncapi/optimizer`) (中文(简体) ).
> 
> **v2是直通图书馆消费者的破解发行.** 错误现已输入包含一个马厩的类 `.code` (单位:千美元)`OptimizerError` 编号 : `OptimizerErrorCode`) 而不是平庸的 `Error` + 键 `console.error`· ; `getReport()` 现在返回 `{ type, elements }[]`; 和 : `@asyncapi/parser` 现在是一个 **依赖性** (安装在旁边). 优化算法和 `getOptimizedDocument()` 行为不变。 见移徙指南: [`docs/optimizer/optimizer-migration.md`](https://github.com/asyncapi/cli/blob/master/docs/optimizer/optimizer-migration.md)。 。 。 .

![npm](https://img.shields.io/npm/v/@asyncapi/optimizer?style=for-the-badge) ![npm](https://img.shields.io/npm/dt/@asyncapi/optimizer?style=for-the-badge)

-   [测试](https://npmcn.com/package/%40asyncapi/optimizer/#readme-testing)
-   [使用量](https://npmcn.com/package/%40asyncapi/optimizer/#readme-usage)
    -   [节点.js](https://npmcn.com/package/%40asyncapi/optimizer/#readme-nodejs)
    -   [生成报告](https://npmcn.com/package/%40asyncapi/optimizer/#readme-generating-report)
    -   [应用建议的修改](https://npmcn.com/package/%40asyncapi/optimizer/#readme-applying-the-suggested-changes)
-   [API 文档](https://npmcn.com/package/%40asyncapi/optimizer/#readme-api-documentation)

## 测试

1.  克隆 CLI 单列 `git clone https://github.com/asyncapi/cli.git`
2.  从 repo 根安装依赖性 `npm i`
3.  构建此软件包 `npm run optimizer:build`,或从 `packages/optimizer` 运行 `npm run example`打开 `examples/index.js` 并修改或添加自己的 AsyncAPI 文档.

## 使用量

### 节点.js

```typescript
import { Optimizer } from '@asyncapi/optimizer'
import type { Report } from '@asyncapi/optimizer'

const yaml = `
asyncapi: 3.0.0
info:
  title: Example Service
  version: 1.0.0
  description: Example Service.
servers:
  production:
    host: 'test.mosquitto.org:{port}'
    protocol: mqtt
    description: Test broker
    variables:
      port:
        description: Secure connection (TLS) is available through port 8883.
        default: '1883'
        enum:
          - '1883'
          - '8883'
operations:
  user/deleteAccount.subscribe:
    action: send
    channel:
      $ref: '#/channels/commentLikedChannel'
channels:
  commentLikedChannel:
    address: comment/liked
    messages:
      commentLikedMessage:
        description: Message that is being sent when a comment has been liked by someone.
        payload:
          type: object
          title: commentLikedPayload
          properties:
            commentId:
              type: string
              description: an id object
              x-origin: ./schemas.yaml#/schemas/idSchema
          x-origin: ./schemas.yaml#/schemas/commentLikedSchema
        x-origin: ./messages.yaml#/messages/commentLikedMessage
    x-origin: ./channels.yaml#/channels/commentLikedChannel`

const optimizer = new Optimizer(yaml)
```

### 生成报告

```typescript
const report = await optimizer.getReport()
/*
v2: getReport() returns { type, elements }[] (not a keyed object).

[
  { type: 'removeComponents', elements: [] },
  { type: 'reuseComponents', elements: [] },
  {
    type: 'moveAllToComponents',
    elements: [
      {
        path: 'channels.commentLikedChannel.messages.commentLikedMessage.payload.properties.commentId',
        action: 'move',
        target: 'components.schemas.idSchema'
      },
      {
        path: 'channels.commentLikedChannel.messages.commentLikedMessage.payload',
        action: 'move',
        target: 'components.schemas.commentLikedSchema'
      },
      {
        path: 'channels.commentLikedChannel.messages.commentLikedMessage',
        action: 'move',
        target: 'components.messages.commentLikedMessage'
      },
      {
        path: 'operations.user/deleteAccount.subscribe',
        action: 'move',
        target: 'components.operations.subscribe'
      },
      {
        path: 'channels.commentLikedChannel',
        action: 'move',
        target: 'components.channels.commentLikedChannel'
      },
      {
        path: 'servers.production',
        action: 'move',
        target: 'components.servers.production'
      }
    ]
  },
  { type: 'moveDuplicatesToComponents', elements: [] }
]
 */
```

### 应用建议的修改

```typescript
const optimizedDocument = optimizer.getOptimizedDocument({
  output: 'YAML',
  rules: {
    reuseComponents: true,
    removeComponents: true,
    moveAllToComponents: true,
    moveDuplicatesToComponents: false,
  },
  disableOptimizationFor: {
    schema: false,
  },
})
/*
the optimizedDocument value will be:

asyncapi: 3.0.0
info:
  title: Example Service
  version: 1.0.0
  description: Example Service.
servers:
  production:
    $ref: '#/components/servers/production'
operations:
  user/deleteAccount.subscribe:
    action: send
    channel:
      $ref: '#/channels/commentLikedChannel'
  user/deleteAccount:
    subscribe:
      $ref: '#/components/operations/subscribe'
channels:
  commentLikedChannel:
    $ref: '#/components/channels/commentLikedChannel'
components:
  schemas:
    idSchema:
      type: string
      description: an id object
      x-origin: ./schemas.yaml#/schemas/idSchema
    commentLikedSchema:
      type: object
      title: commentLikedPayload
      properties:
        commentId:
          $ref: '#/components/schemas/idSchema'
      x-origin: ./schemas.yaml#/schemas/commentLikedSchema
  messages:
    commentLikedMessage:
      description: Message that is being sent when a comment has been liked by someone.
      payload:
        $ref: '#/components/schemas/commentLikedSchema'
      x-origin: ./messages.yaml#/messages/commentLikedMessage
  operations: {}
  channels:
    commentLikedChannel:
      address: comment/liked
      messages:
        commentLikedMessage:
          $ref: '#/components/messages/commentLikedMessage'
      x-origin: ./channels.yaml#/channels/commentLikedChannel
  servers:
    production:
      host: test.mosquitto.org:{port}
      protocol: mqtt
      description: Test broker
      variables:
        port:
          description: Secure connection (TLS) is available through port 8883.
          default: '1883'
          enum:
            - '1883'
            - '8883'
 */
```

## API 文档

要使用优化器优化文件, 您只需要导入 `Optimizer` 课。 使用其两种方法获取报告`getReport()`)并获得优化文档(`getOptimizedDocument()`) (中文(简体) ).

见 [API 文档](https://npmcn.com/package/%40asyncapi/optimizer/API.md) 以更多实例和完整的 API 参考信息.

## 常见问题

### @asyncapi/optimizer 是什么？

此库将优化 AsyncAPI 规格文件 \.

### 如何安装 @asyncapi/optimizer？

在项目目录运行 npm install @asyncapi/optimizer，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@asyncapi/parser（^3\.6\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @asyncapi/optimizer 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @asyncapi/optimizer 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @asyncapi/optimizer 可以商用吗？

@asyncapi/optimizer 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @asyncapi/optimizer 的下载量有多少？

根据 npm 官方下载统计，@asyncapi/optimizer 在 2026/10/07 – 2026/11/05 这 30 天内被下载 293,339 次，日均约 9,778 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @asyncapi/optimizer 还在维护吗？

最新版本 2\.0\.1 发布于 2026/11/02（5 天前）；至今共发布 56 个版本，其中过去 12 个月发布了 4 个；首次发布于 2021/08/10。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

