# @anycable/turbo-stream 中文文档

规范地址：https://npmcn.com/package/%40anycable/turbo-stream/

版本：0\.8\.1
npm 元数据更新时间：2025-02-20T04:43:18.303Z
中文译文更新时间：2026-11-06T07:48:30.380Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40anycable/turbo-stream
原文对照：https://npmcn.com/package/%40anycable/turbo-stream/?lang=original
项目主页：https://anycable.io/
源码仓库：https://github.com/anycable/anycable-client

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

- 包体积（解压后）：16.6 kB，11 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=8\.3\.0
- 运行依赖：1 个
- peer 依赖：@hotwired/turbo \>= 7\.0
- 首次发布：2022-04-30T18:15:23.336Z
- 最新版本发布：2025-02-20T04:43:18.117Z
- 近 30 天下载量：106057（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：21（近 12 个月 0 个）

## 中文简介

支持涡轮流的 AnyCable客户端插件

## 安装

```sh
npm install @anycable/turbo-stream
```

也可以使用：`pnpm add @anycable/turbo-stream`、`yarn add @anycable/turbo-stream`、`bun add @anycable/turbo-stream`

## README

[![npm version](https://badge.fury.io/js/%40anycable%2Fturbo-stream.svg)](https://badge.fury.io/js/%40anycable%2Fturbo-stream)

# 有线涡流

此软件包提供了 AnyCable 客户端集成 [涡轮流](https://turbo.hotwired.dev/reference/streams)。 。 。 .

默认 `@hotwired/turbo-rails` 软件包不允许您用自定义消费者执行替换默认的动作有线客户端.

> 您可以从 AnyCasts 插曲中更多地了解自定义涡流集成背后的动机 ["利用有线客户自动刷新信使"](https://anycable.io/blog/anycasts-using-anycable-client/)

**注:** 确保你没有进口 `@hotwired/turbo-rails` 或使用自定义标签名: Hotwire 的软件包暗中登记自定义元素,无法覆盖.

## 使用量

假设你有一个 `cable` 实例定义,用于激活涡轮流元素,您需要添加以下代码:

```js
import { start } from "@anycable/turbo-stream"
// This is your cable instance
import cable from "cable"
// Explicitly activate stream source elements
start(cable)
```

这种方法允许您控制何时(以及如何)从 `<turbo-cable-stream-source>` HTML 元素.

**不需要服务器侧修改**。我们支持所有标准功能:通过自定义频道类和订阅参数.

## 兼容性与 `@hotwired/turbo-rails`

我们的集成旨在让API与官方软件包兼容,这意味着HTML元素及其属性的识别和解释与使用相同 `@hotwired/turbo-rails`。 。 。 .

一个微妙但重要的区别是 **`@anycable/turbo-stream` 不激活添加到临时涡轮缓存页面中的流元素**。这样我们就可以避免不必要的订阅/订阅和潜在的种族条件.

## 高级配置

### 延迟未订阅

在使用涡轮驱动器进行导航时,常见的情况是将一个流源元素附着在同一流上,以在新旧HTML中同时出现. 为了避免对下行流重新订阅,我们可以在导航期间通过推迟订阅来保留订阅 `unsubscribe` 电话(或更确切地说, `channel.disconnect()`) (中文(简体) ). 因此,我们可以避免不必要的Action Cable命令,并避免在重新订阅之间丢失到的信息. 您必须选择使用此特性 :

```js
import { start } from "@anycable/turbo-stream"
import cable from "cable"

start(cable, { delayedUnsubscribe: true }) // default is 300ms

start(cable, { delayedUnsubscribe: 1000 }) // Custom number of milliseconds
```

### 随附 `X-Socket-ID` turbo 请求的页眉

您可以用当前套接字会话 ID 自动为所有 Turbo 请求添加一个信头 。 这可以用来表演 **对他人的广播** (见 [铁路一体化文件](https://docs.anycable.io/rails/getting_started?id=action-cable-extensions):

```js
import { start } from "@anycable/turbo-stream"
import cable from "cable"

start(cable, { requestSocketIDHeader: true })

// You can also specify a custom header name
// start(cable, { requestSocketIDHeader: 'X-My-Socket-ID' })
```

### 自定义频道类

您定义 Turbo Streams 订阅的自定义 JS 频道类 :

```js
import { TurboChannel } from "@anycable/turbo-stream"

class CustomTurboChannel extends TurboChannel {
  // Constructor receives the current HTML element (turbo-cable-stream-source),
  // a channel name (Turbo::StreamsChannel) by default and subscription params
  constructor(element, channelName, params) {
    // You can override the server-side channel name
    super(element, 'MyTurboChannel', params)
    // Additional state configuration goes here
    this.totalActions = 0
  }

  // You can override receive function to intercept actions
  receive(message) {
    this.totalActions++

    // Ignore every second message
    if (this.totalActions % 2 === 0) return

    // Fallback to the default behaviour,
    // which sends the action to Turbo
    super.receive(message)
  }
}
```

另一个例子是一个在操作前记录所有动作的通道:

```js
class LogChannel extends TurboChannel {
  receive(message) {
    console.log("TURBO ACTION", message)
    super.receive(message)
  }
}

start(cable, {channelClass: LogChannel})
```

### 自定义标签

您可以使用自定义的 Turbo Streams 源元素标签名 。 其中一个用法是使用不同的联署材料渠道进行不同的标记:

```js
// Assuming you have some special channel class
import { TurboPresenceChannel } from './channel.js'
import { start } from "@anycable/turbo-stream"

import cable from "cable"

// Default behaviour
start(cable)

// Custom behaviour
start(cable, { tagName: 'turbo-presence-source', channelClass: TurboPresenceChannel })
```

**注:** 您需要创建自定义的 Rails 助手来渲染自定义元素 。 例如:

```ruby
def turbo_presence_stream_from(*streamables, **attributes)
  attributes[:channel] = attributes[:channel]&.to_s || "Turbo::StreamsChannel"
  attributes[:"signed-stream-name"] = Turbo::StreamsChannel.signed_stream_name(streamables)

  tag.turbo_presence_source(**attributes)
end
```

## 常见问题

### @anycable/turbo-stream 是什么？

支持涡轮流的 AnyCable客户端插件

### 如何安装 @anycable/turbo-stream？

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

### @anycable/turbo-stream 支持 TypeScript 吗？

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

### @anycable/turbo-stream 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @anycable/turbo-stream 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=8\.3\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @anycable/turbo-stream 可以商用吗？

@anycable/turbo-stream 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @anycable/turbo-stream 的下载量有多少？

根据 npm 官方下载统计，@anycable/turbo-stream 在 2026/10/06 – 2026/11/04 这 30 天内被下载 106,057 次，日均约 3,535 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @anycable/turbo-stream 还在维护吗？

最新版本 0\.8\.1 发布于 2025/02/20（1\.7 年前）；至今共发布 21 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/05/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

