# @gramio/format 中文文档

规范地址：https://npmcn.com/package/%40gramio/format/

版本：0\.12\.1
npm 元数据更新时间：2026-09-09T23:12:42.377Z
中文译文更新时间：2026-11-16T21:56:56.081Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40gramio/format
原文对照：https://npmcn.com/package/%40gramio/format/?lang=original
项目主页：https://gramio.dev/formatting.html
源码仓库：https://github.com/gramiojs/format

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

- 包体积（解压后）：355 kB，30 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：marked ^15\.0\.11，node-html-parser \>=6\.0\.0
- 首次发布：2024-02-10T21:42:10.146Z
- 最新版本发布：2026-09-09T23:12:41.973Z
- 近 30 天下载量：57592（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 11 个）

## 中文简介

Telegram Bot API 文本格式化库

## 安装

```sh
npm install @gramio/format
```

也可以使用：`pnpm add @gramio/format`、`yarn add @gramio/format`、`bun add @gramio/format`

## README

# @ gramio/ 格式

图书馆 [格式化](https://core.telegram.org/bots/api#messageentity) telegram Bot API 的文本。 用在引擎盖下 [语法](https://gramio.dev/) 框架,但它是框架不可知的.

[![npm](https://img.shields.io/npm/v/@gramio/format?logo=npm&style=flat&labelColor=000&color=3b82f6)](https://www.npmjs.org/package/@gramio/format) [![JSR](https://jsr.io/badges/@gramio/format)](https://jsr.io/@gramio/format) [![JSR Score](https://jsr.io/badges/@gramio/format/score)](https://jsr.io/@gramio/format)

## 安装

```sh
npm install @gramio/format
# or
bun add @gramio/format
```

## 概览

`@gramio/format` 正在建设 [`MessageEntity`](https://core.telegram.org/bots/api#messageentity) 对象与文本相并列,所以您无需手动跟踪字符偏移。 所有格式化者自由地作曲——像你们喜欢的那样深入地筑巢.

```ts
import { format, bold, italic, link, spoiler } from "@gramio/format";

const msg = format`${bold`Hi!`}

Can ${italic("you")} help ${spoiler`me`}?

Can you give me a ${link("star", "https://github.com/gramiojs/gramio")}?`;

// msg.text     → the plain string
// msg.entities → ready-to-send MessageEntity[]
```

* * *

## 模板文字

### `format`

条从每行(安全到来源内的缩进)引出缩进.

```ts
import { format, bold, italic } from "@gramio/format";

format`Hello ${bold("world")}!`
// text: "Hello world!"
// entities: [{ type: "bold", offset: 6, length: 5 }]
```

### `formatSaveIndents`

与 `format` 但保留了所有的空白 完全如所写.

```ts
import { formatSaveIndents, code } from "@gramio/format";

formatSaveIndents`Run:\n    ${code("bun install")}`
```

* * *

## 格式化器

每个前题都接受一个简单的字符串,一个 `FormattableString`,或标记模板文字.

```ts
bold("text")
bold`text`
bold(italic("text"))   // nested: bold wraps italic
```

| 主题 | 电报实体 | 页:1 |
| --- | --- | --- |
| `bold` | `bold` | 无法结合 `code` 编号 : `pre` |
| `italic` | `italic` | 无法结合 `code` 编号 : `pre` |
| `underline` | `underline` | 无法结合 `code` 编号 : `pre` |
| `strikethrough` | `strikethrough` | 无法结合 `code` 编号 : `pre` |
| `spoiler` | `spoiler` | 无法结合 `code` 编号 : `pre` |
| `blockquote` | `blockquote` | 无法嵌入 |
| `expandableBlockquote` | `expandable_blockquote` | 无法嵌入 |
| `code` | `code` | 内置单空间; 无法与其他空间合并 |
| `pre(text, lang?)` | `pre` | 代码块; 语法突出显示的可选语言 |
| `link(text, url)` | `text_link` | 无法结合 `code` 编号 : `pre` |
| `mention(text, user)` | `text_mention` |  |
| `customEmoji(emoji, id)` | `custom_emoji` | 需要在断层上购买用户名 |

### 实例

```ts
import {
    bold, italic, underline, strikethrough, spoiler,
    blockquote, expandableBlockquote,
    code, pre, link, mention, customEmoji,
    format,
} from "@gramio/format";

bold`Important`
italic`Subtle`
underline`Marked`
strikethrough`Removed`
spoiler`Secret`

blockquote`A quote from someone wise.`
expandableBlockquote`A very long quote that can be collapsed.`

code`npm install`
pre("console.log('hi')", "js")

link("GramIO", "https://gramio.dev")
mention("John", { id: 1, is_bot: false, first_name: "John" })
customEmoji("⚔️", "5222106016283378623")

// Compose freely
format`${bold("Price")}: ${italic("$42")}\nSee ${link("docs", "https://gramio.dev")}`
```

* * *

## `join` ——格式化阵列

阵列 `.join()` 丢弃实体。 使用 `join` 相反:

```ts
import { join, bold, format } from "@gramio/format";

const items = ["apple", "banana", "cherry"];

format`Shopping list:\n${join(items, (item) => bold(item), "\n")}`;
// text:     "Shopping list:\napple\nbanana\ncherry"
// entities: bold on each item at the correct offsets
```

第三个参数是分隔符( 默认) `", "`) (中文(简体) ). 返回时 `null`, (中文(简体) ), `undefined`,或 `false` 跳过项目.

* * *

## `markdownToFormattable` 平面平面结构

将 Markdown 字符串转换为 a `FormattableString` 与适当的实体。 当您的内容来自 Markdown 源( 如 API docs, 用户输入) 时有用 .

**要求数 [`marked`](https://marked.js.org/) 作为同伴依赖:**

```sh
npm install marked
```

```ts
import { markdownToFormattable } from "@gramio/format/markdown";

const result = markdownToFormattable(
    "# Title\n\n**bold** and *italic*\n\n> Blockquote\n\n[link](https://gramio.dev)"
);

// result.text     → "Title\n\nbold and italic\n\nBlockquote\n\nlink"
// result.entities → bold, italic, blockquote, text_link at correct offsets
```

### 支持的标记下元素

| 标记 | 结果 |
| --- | --- |
| `**text**` 编号 : `__text__` | 粗体 |
| `*text*` 编号 : `_text_` | 斜体 |
| `~~text~~` | 击穿 |
| `` `code` `` | 内置代码 |
| ` ```lang\n...\n``` ` | 预设块( 有可选语言) |
| `> text` | 块引用 |
| `[text](url)` | 链接 |
| `![alt](url)` | 链接(图像-文本链接) |
| `# Heading` . `###### Heading` | 粗体 |
| `- item` 编号 : `1. item` | 列表中包含项目符号/数字前缀 |

* * *

## `htmlToFormattable` —— HTML —— 格式表

将 HTML 字符串转换为 a `FormattableString`。为 HTML 设计,由丰富文本编辑器如 **提示**, (中文(简体) ), **表达器**,或 **奎尔**。 。 。 .

**要求数 [`node-html-parser`](https://github.com/taoqf/node-html-parser) 作为同伴依赖:**

```sh
npm install node-html-parser
```

```ts
import { htmlToFormattable } from "@gramio/format/html";

const result = htmlToFormattable(
    "<p><strong>Hello</strong> <em>world</em></p>"
);

// result.text     → "Hello world"
// result.entities → [bold offset=0 len=5, italic offset=6 len=5]
```

### 支持的 HTML 元素

| 元素 | 结果 | 页:1 |
| --- | --- | --- |
| `<strong>`, (中文(简体) ), `<b>` | 粗体 |  |
| `<em>`, (中文(简体) ), `<i>` | 斜体 |  |
| `<u>` | 下划线 |  |
| `<s>`, (中文(简体) ), `<del>`, (中文(简体) ), `<strike>` | 击穿 |  |
| `<code>` | 内置代码 | 不在里面的时候 `<pre>` |
| `<pre><code class="language-js">` | 预设块 | 从 `language-*` 类 |
| `<blockquote>` | 块引用 | 连续处理的儿童 |
| `<a href="...">` | 链接 |  |
| `<h1>` . `<h6>` | 粗体 |  |
| `<p>`, (中文(简体) ), `<div>` | 透明包装 | 儿童与 `""` |
| `<br>` | `\n` |  |
| `<ul>` | 未排序列表 | 前缀的项目 `-` |
| `<ol start="N">` | 命令列表 | 编号项目 `start` |

根部的块级元素由 `\n\n`。清单项目由 `\n`内嵌列表得到支持并缩进 `\n` 在子列表之前.

### TipTap 示例

```ts
import { htmlToFormattable } from "@gramio/format/html";

const html = `
<h1>Release notes</h1>
<p>Version <strong>2.0</strong> is out with <em>exciting</em> changes:</p>
<ul>
  <li><p>New <code>htmlToFormattable</code> function</p></li>
  <li><p>Performance improvements</p></li>
</ul>
<p>Read the <a href="https://gramio.dev">full docs</a>.</p>
`;

const result = htmlToFormattable(html);
// Sends correctly formatted message to Telegram with all entities intact
```

* * *

## 使用Telegram Bot API

这个 `FormattableString` 对象有 `.text` 财务报告和审定财务报表 `.entities` 直接映射到Telegram的属性 `sendMessage` 参数 :

```ts
import { format, bold, link } from "@gramio/format";

const msg = format`Check out ${bold(link("GramIO", "https://gramio.dev"))}!`;

await bot.api.sendMessage({
    chat_id: chatId,
    text: msg.text,
    entities: msg.entities,
});
```

与 [语法](https://gramio.dev/) 你可以通过 `FormattableString` 直接 :

```ts
bot.on("message", (ctx) => {
    ctx.send(format`Hello ${bold(ctx.from.first_name)}!`);
});
```

* * *

## 丰富的信息和本地表格

对于Telegram Rich Messages ,请使用结构化 `table()` 需要本地语言时的帮助 `InputRichBlockTable` 而不是 Markdown 文本 :

```ts
import { blocks, table } from "@gramio/format/rich";

const report = blocks([
    blocks.heading(1, "Release report"),
    table(
        [["Package", "Version"], ["gramio", "0.14.0"]],
        { bordered: true, striped: true, compact: true, align: ["left", "right"] },
    ),
]);

ctx.send(report);
```

`table()` 也可以直接发送。 第一行默认为页眉,单元格对齐 默认为 `left`编号 :`top`启用 `blocks.cell("Total", { colSpan: 2 })` 为了跨度。 前一个 Markdown/GFM 序列器为 `markdownTable()` 标记下成分 `rich([...])`。 。 。 .

这是一个突破性的变化 从 `@gramio/format` 0.11: (中文(简体) ) `table()` 用于生产Markdown/GFM. 重命名现有的 Markdown 呼叫到 `markdownTable()` 升级到0.12时.

对于由您自己信任的序列器生成的完整的Markdown/HTML字符串,请使用 `rawRich()`· ; 它保留了保险箱的语法 `rich\`. ' 尔时`tag escapes. Never pass untrusted text to`(原始内容存档于2017-03-21). 生Rich().

使用时 `rowSpan`中,在以下行中省略所覆盖的单元格;列对齐跟随 逻辑表网格.

* * *

## 另见

-   [完整文档](https://gramio.dev/formatting.html)
-   [GramIO框架](https://gramio.dev/)
-   [电报信件实体文件](https://core.telegram.org/bots/api#messageentity)

## 常见问题

### @gramio/format 是什么？

Telegram Bot API 文本格式化库

### 如何安装 @gramio/format？

在项目目录运行 npm install @gramio/format，或使用 pnpm add / yarn add / bun add。

### @gramio/format 支持 TypeScript 吗？

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

### @gramio/format 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @gramio/format 可以商用吗？

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

### @gramio/format 的下载量有多少？

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

### @gramio/format 还在维护吗？

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

