# @11ty/gray-matter 中文文档

规范地址：https://npmcn.com/package/%4011ty/gray-matter/

版本：3\.0\.0
npm 元数据更新时间：2026-07-29T22:14:44.658Z
中文译文更新时间：2026-11-05T16:56:26.567Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%4011ty/gray-matter
原文对照：https://npmcn.com/package/%4011ty/gray-matter/?lang=original
项目主页：https://github.com/11ty/gray-matter
源码仓库：https://github.com/11ty/gray-matter

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

- 包体积（解压后）：35.8 kB，13 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=11
- 运行依赖：2 个
- 首次发布：2025-05-12T15:10:07.375Z
- 最新版本发布：2026-07-29T22:14:44.480Z
- 近 30 天下载量：3387374（2026-10-04 至 2026-11-02，npm 官方下载统计）
- 已发布版本数：6（近 12 个月 4 个）

## 中文简介

从字符串或文件中解析前题 。 快速,可靠和易于使用. 默认情况下parses YAML前事,但也支持YAML,JSON,TOML Front-Matter,有设置自定义分隔符的选项. 用于金属匠、组装、动词和许多其他

## 安装

```sh
npm install @11ty/gray-matter
```

也可以使用：`pnpm add @11ty/gray-matter`、`yarn add @11ty/gray-matter`、`bun add @11ty/gray-matter`

## README

# @ 11ty/ gray- matter

减少和维持的叉子 [`gray-matter` 原由乔恩·施林克特(Jon Schlinkert)](https://www.npmjs.com/package/gray-matter)。 。 。 .

当前差异 :

-   [上流软件包最后一次发布于2019年](https://github.com/jonschlinkert/gray-matter/releases/tag/4.0.2)。 。 。 .
-   升级 `js-yaml` 向 v4 主要版本
-   内部使用 Uint8Array 而不是 Node- env 特定缓冲器来进行更多的运行时间相容性.
-   删除 `javascript` 前事项类型( 取消对 `eval`(中文(简体) )

> 从字符串或文件中解析前题 。 快速,可靠和易于使用. 默认情况下将 YAML 前置事项解析,但也支持 YAML, JSON, 或 TOML Front- Matter, 选项设置自定义分隔符 .

## 安装

安装方式 [无](https://www.npmjs.com/)数字 :

```sh
$ npm install --save @11ty/gray-matter
```

## 抬头!

请看 [更改日志](https://npmcn.com/package/%4011ty/gray-matter/CHANGELOG.md) 来了解在v3.0中所做的改变.

  

## 这有什么用?

**运行此示例**

以下示例中的 HTML 添加到 `example.html`,然后将以下代码添加到 `example.js` 运行 `$ node example` (无 `$`:

```js
const fs = require('fs');
const matter = require('@11ty/gray-matter');
const str = fs.readFileSync('example.html', 'utf8');
console.log(matter(str));
```

用前题转换字符串, 像这样 :

```handlebars
---
title: Hello
slug: home
---
<h1>Hello world!</h1>
```

进入这样的物体:

```js
{
  content: '<h1>Hello world!</h1>',
  data: {
    title: 'Hello',
    slug: 'home'
  }
}
```

## 为什么用灰色的东西?

-   **简单**: 主函数取字符串并返回对象
-   **准确**: 优于依赖regex进行解析的前题解析器来捕捉和处理边缘案件
-   **快点**: 比其它使用正则正则解析器进行解析的前事解析器更快
-   **灵活**: 默认情况下, 灰色物质能够解析 [也门](https://github.com/nodeca/js-yaml), (中文(简体) ), [贾森](http://en.wikipedia.org/wiki/Json) 和 JavaScript 前题。 但别的地方 [发动机](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsengines) 可添加.
-   **可扩展**: 使用 [自定义分隔符](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsdelimiters),或添加对 [任何语言](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsengines)一样 [移动](http://github.com/mojombo/toml)。 。 。 .
-   **作战测试**: 由 [组装](https://github.com/assemble/assemble), (中文(简体) ), [金属匠](https://github.com/segmentio/metalsmith), (中文(简体) ), [花环](https://github.com/phenomic/phenomic), (中文(简体) ), [动词](https://github.com/assemble/verb), (中文(简体) ), [生成](https://github.com/generate/generate), (中文(简体) ), [更新](https://github.com/update/update) 还有其他许多.

**理由**

**为什么我们一开始要创造出灰色的东西?**

我们在尝试了其他不符合我们的标准和要求的图书馆之后创造了灰色的东西.

一些图书馆满足了大部分要求,但 _没有人见过他们_。 。 。 .

**这是最重要的**数字 :

-   可用,即使不简单
-   使用可靠且支持良好的库来解析 YAML
-   除YAML外支持其他语言
-   支持将字符串回YAML 或其他语言
-   内容不存在时不要失败
-   不要失败,没有前题
-   别用regex来解析. 这是一个相对简单的解析操作,而regex是最慢和最容易出错的方法.
-   直接读取 YAML 文件没有问题
-   内容复杂没有问题,包括: **非前事事项** 包含 YAML 前置物质示例的有栅栏的代码块 。 其他分析失败了.
-   支持将字符串恢复到前题 。 这对折叠,更新属性等都有用.
-   允许自定义分界器,当它是避免分界器相撞所必需的.
-   返回至少具有这三种属性的对象时:
    -   `data`:解析出 YAML 前题, 作为 JSON 对象
    -   `content`: 内容为字符串,没有前题
    -   `orig`:"原始"内容 (用于调试)

## 使用量

使用普通JS :

```js
const matter = require('@11ty/gray-matter');
```

或无害环境管理:

```js
import matter = require('@11ty/gray-matter');
// OR
import * as matter from '@11ty/gray-matter';
```

通过字符串和 [选项](https://npmcn.com/package/%4011ty/gray-matter/#readme-options) 改为灰色物质 :

```js
console.log(matter('---\ntitle: Front Matter\n---\nThis is content.'));
```

回返情况:

```js
{
  content: '\nThis is content.',
  data: {
    title: 'Front Matter'
  }
}
```

更多关于下一节中返回的对象.

* * *

## 返回对象

灰色物质返回 a `file` 对象,其属性如下.

**可假设**

-   `file.data` **{对象}**: 通过解析前题创建的对象
-   `file.content` **{string}(string ) , \[ 弦叫 \]**: 输入字符串,与 `matter` 剥去
-   `file.excerpt` **{string}(string ) , \[ 弦叫 \]**: 节选,如果 [在选项上定义](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsexcerpt)
-   `file.empty` **{string}(string ) , \[ 弦叫 \]**:当前题为"空"时(要么全部为白空,完全没有,要么只是评论和没有数据),原始字符串设置在这个属性上. 见 [65号](https://github.com/jonschlinkert/gray-matter/issues/65) 关于使用案例的细节.
-   `file.isEmpty` **(保罗)**: 前题为空时为真 .

**不可假定**

此外,在对象上还添加了以下非数字属性来帮助调试.

-   `file.orig` **{Uint8箭头}**: 原始输入字符串(或 Uint8Array)
-   `file.language` **{string}(string ) , \[ 弦叫 \]**:被解析的前题语言. `yaml` 是默认
-   `file.matter` **{string}(string ) , \[ 弦叫 \]**页:1 _原始内容_未解析前事项字符串
-   `file.stringify` **{职能}**数字 : [字符串](https://npmcn.com/package/%4011ty/gray-matter/#readme-stringify) 转换文件 `file.data` 以给定语言将字符串包入分隔符并预留到 `file.content`。 。 。 .

## 运行示例

如果你想试一下这些例子 首先克隆出灰色物质 `my-project` (或随所取地):

```sh
$ git clone https://github.com/jonschlinkert/gray-matter my-project
```

CD 进入 `my-project` 并安装依赖性 :

```sh
$ cd my-project && npm install
```

然后运行任何 [实例](https://npmcn.com/package/%4011ty/gray-matter/examples) 以查看灰色物质如何工作:

```sh
$ node examples/<example_name>
```

**与实例的链接**

-   [节选分隔符](https://npmcn.com/package/%4011ty/gray-matter/examples/excerpt-separator.js)
-   [节选字符串](https://npmcn.com/package/%4011ty/gray-matter/examples/excerpt-stringify.js)
-   [节选](https://npmcn.com/package/%4011ty/gray-matter/examples/excerpt.js)
-   [日记](https://npmcn.com/package/%4011ty/gray-matter/examples/javascript.js)
-   [json 字符串](https://npmcn.com/package/%4011ty/gray-matter/examples/json-stringify.js)
-   [乔森](https://npmcn.com/package/%4011ty/gray-matter/examples/json.js)
-   [恢复空](https://npmcn.com/package/%4011ty/gray-matter/examples/restore-empty.js)
-   [节选](https://npmcn.com/package/%4011ty/gray-matter/examples/sections-excerpt.js)
-   [节次](https://npmcn.com/package/%4011ty/gray-matter/examples/sections.js)
-   [汤姆尔](https://npmcn.com/package/%4011ty/gray-matter/examples/toml.js)
-   [雅姆勒字符串](https://npmcn.com/package/%4011ty/gray-matter/examples/yaml-stringify.js)
-   [雅姆尔](https://npmcn.com/package/%4011ty/gray-matter/examples/yaml.js)

## API 密码

### [事项](https://npmcn.com/package/%4011ty/gray-matter/index.js#L29)

用字符串或对象 `content` 属性,从字符串中取出并解析前题,然后返回对象 `data`, (中文(简体) ), `content` 其他项目 [有用的属性](https://npmcn.com/package/%4011ty/gray-matter/#readme-returned-object)。 。 。 .

**参数**

-   `input` **{对象}**: 字符串,或对象 `content` 字符串
-   `options` **{对象}**
-   `returns` **{对象}**

**示例**

```js
const matter = require('@11ty/gray-matter');
console.log(matter('---\ntitle: Home\n---\nOther stuff'));
//=> { data: { title: 'Home'}, content: 'Other stuff' }
```

### [字符串](https://npmcn.com/package/%4011ty/gray-matter/index.js#L160)

将对象字符串为 YAML 或指定语言, 并附加到指定字符串中 。 默认情况下,只有YAML和JSON可以被字符串. 见 [发动机](https://npmcn.com/package/%4011ty/gray-matter/#readme-engines) 区域来学习如何将其他语言字符串化.

**参数**

-   `file` **目标**: 附加到字符串前事项的内容字符串, 或文件对象 `file.content` 绳子.
-   `data` **{对象}**: 前题需要字符串.
-   `options` **{对象}**数字 : [选项](https://npmcn.com/package/%4011ty/gray-matter/#readme-options) 传递到灰色物质和 [日-亚姆尔](https://github.com/nodeca/js-yaml)。 。 。 .
-   `returns` **{string}(string ) , \[ 弦叫 \]**: 返回通过用分隔符将字符串相接而创建的字符串,并将它附加到给定字符串中.

**示例**

```js
console.log(matter.stringify('foo bar baz', {title: 'Home'}));
// results in:
// ---
// title: Home
// ---
// foo bar baz
```

### [读取](https://npmcn.com/package/%4011ty/gray-matter/index.js#L178)

同步读取文件系统的文件并解析前题 。 返回与 [主要函数](https://npmcn.com/package/%4011ty/gray-matter/#readme-matter)。 。 。 .

**参数**

-   `filepath` **{string}(string ) , \[ 弦叫 \]**: 要读取的文件路径 .
-   `options` **{对象}**数字 : [选项](https://npmcn.com/package/%4011ty/gray-matter/#readme-options) 传递到灰色的东西.
-   `returns` **{对象}**: 回归 [对象](https://npmcn.com/package/%4011ty/gray-matter/#readme-returned-object) 与 `data` 财务报告和审定财务报表 `content`

**示例**

```js
const file = matter.read('./content/blog-post.md');
```

### [测试](https://npmcn.com/package/%4011ty/gray-matter/index.js#L193)

如果给定返回真 `string` 有前题.

**参数**

-   `string` **{string}(string ) , \[ 弦叫 \]**
-   `options` **{对象}**
-   `returns` **(保罗)**: 如果前题存在, 则为真 .

## 选项

### 选项。节选

**类型**数字 : `Boolean|Function`

**默认**数字 : `undefined`

摘录一个直接跟随前事的节选,或者在没有前事的情况下是字符串中的第一件事.

如果设置为 `excerpt: true`它会寻找前题划界器, `---` 默认,并抓住一切导致它.

**示例**

```js
const str = '---\nfoo: bar\n---\nThis is an excerpt.\n---\nThis is content';
const file = matter(str, { excerpt: true });
```

成果:

```js
{
  content: 'This is an excerpt.\n---\nThis is content',
  data: { foo: 'bar' },
  excerpt: 'This is an excerpt.\n'
}
```

您也可以设置 `excerpt` 到一个函数。 此函数使用“ 文件” 和“ 选项” 作为参数, 以控制从内容中提取节选 .

**示例**

```js
// returns the first 4 lines of the contents
function firstFourLines(file, options) {
  file.excerpt = file.content.split('\n').slice(0, 4).join(' ');
}

const file =  matter([
  '---',
  'foo: bar',
  '---',
  'Only this',
  'will be',
  'in the',
  'excerpt',
  'but not this...'
].join('\n'), {excerpt: firstFourLines});
```

成果:

```js
{
  content: 'Only this\nwill be\nin the\nexcerpt\nbut not this...',
  data: { foo: 'bar' },
  excerpt: 'Only this will be in the excerpt'
}
```

### 选项.节选 分隔符

**类型**数字 : `String`

**默认**数字 : `undefined`

定义用于节选的自定义分隔符 .

```js
console.log(matter(string, {excerpt_separator: '<!-- end -->'}));
```

**示例**

以下 HTML 字符串 :

```html
---
title: Blog
---
My awesome blog.
<!-- end -->
<h1>Hello world</h1>
```

成果:

```js
{
  data: { title: 'Blog'},
  excerpt: 'My awesome blog.',
  content: 'My awesome blog.\n<!-- end -->\n<h1>Hello world</h1>'
}
```

### 选项

定义用于解析和/或字符串前题的自定义引擎 .

**类型**数字 : `Object` 发动机对象

**默认**数字 : `JSON`, (中文(简体) ), `YAML` 财务报告和审定财务报表 `JavaScript` 默认已处理.

**引擎格式**

发动机可以是具有下列特性的物体: `parse` 和(可选) `stringify` 方法,或仅用于解析的函数.

**实例**

```js
const toml = require('toml');

/**
 * defined as a function
 */

const file = matter(str, {
  engines: {
    toml: toml.parse.bind(toml),
  }
});

/**
 * Or as an object
 */

const file = matter(str, {
  engines: {
    toml: {
      parse: toml.parse.bind(toml),

      // example of throwing an error to let users know stringifying is
      // not supported (a TOML stringifier might exist, this is just an example)
      stringify: function() {
        throw new Error('cannot stringify to TOML');
      }
    }
  }
});

console.log(file);
```

### 选项。语言

**类型**数字 : `String`

**默认**数字 : `yaml`

定义用于解析前题的引擎 .

```js
console.log(matter(string, {language: 'toml'}));
```

**示例**

以下 HTML 字符串 :

```html
---
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---
This is content
```

成果:

```js
{ content: 'This is content',
  excerpt: '',
  data:
   { title: 'TOML',
     description: 'Front matter',
     categories: 'front matter toml' } }
```

**动态语言检测**

灰色物质不会定义选项上的语言,而是会自动检测第一个分隔符后定义的语言并选择用于解析的正确引擎.

```html
---toml
title = "TOML"
description = "Front matter"
categories = "front matter toml"
---
This is content
```

### 选项。界限

**类型**数字 : `String`

**默认**数字 : `---`

打开和关闭的分隔符可以作为字符串的数组传递.

**示例**

```js
// format delims as a string
matter.read('file.md', {delims: '~~~'});
// or an array (open/close)
matter.read('file.md', {delims: ['~~~', '~~~']});
```

将解析:

```html
~~~
title: Home
~~~
This is the {{title}} page.
```

## 折旧选项

### 选项。lang

减号,请使用 [选项。语言](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionslanguage) 换句话说.

### 选项.delims

减号,请使用 [选项。界限](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsdelimiters) 换句话说.

### 选项。参数

减号,请使用 [选项](https://npmcn.com/package/%4011ty/gray-matter/#readme-optionsengines) 换句话说.

## 关于

**捐款**

拉出请求和星星总是受欢迎的. 对于错误和特性请求, [请创建一个问题](https://npmcn.com/package/issues/new)。 。 。 .

**运行测试**

运行和审查单元测试是熟悉图书馆及其API的好办法。 您可以使用以下命令安装依赖性并运行测试:

```sh
$ npm install && npm test
```

### 贡献者

| **提交** | **贡献者** |
| --- | --- |
| 179国道 | [扬施林克特](https://github.com/jonschlinkert) |
| 第13条 | [罗伯特马萨约利](https://github.com/robertmassaioli) |
| 第7条 | [罗布洛克](https://github.com/RobLoach) |
| 页:1 | [鸽子](https://github.com/doowb) |
| 页:1 | [{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}嘿 哥们](https://github.com/heymind) |
| 3个 | [极乐世界](https://github.com/aljopro) |
| 3个 | [摇摆机器人](https://github.com/shawnbot) |
| 2个 | [矩形](https://github.com/reccanti) |
| 2个 | [顶点](https://github.com/onokumus) |
| 2个 | [moo克语name](https://github.com/moozzyk) |
| 2个 | [阿杰马瑟](https://github.com/ajaymathur) |
| 1个 | [阿杰迪32号](https://github.com/Ajedi32) |
| 1个 | [阿赖尔](https://github.com/arlair) |
| 1个 | [开萨](https://github.com/caesar) |
| 1个 | [扬·斯通克勒](https://github.com/ianstormtaylor) |
| 1个 | [克立方米](https://github.com/qm3ster) |
| 1个 | [扎克瓦利语name](https://github.com/zachwhaley) |

### 作者

**乔恩·斯林克特**

-   [GitHub 配置文件](https://github.com/jonschlinkert)
-   [推特简介](https://twitter.com/jonschlinkert)
-   [链接到配置文件](https://linkedin.com/in/jonschlinkert)

### 许可证

版权 2023, [乔恩·斯林克特](https://github.com/jonschlinkert)。 。 。 . 释放 [MIT 许可证](https://npmcn.com/package/%4011ty/gray-matter/LICENSE)。 。 。 .

## 常见问题

### @11ty/gray-matter 是什么？

从字符串或文件中解析前题 。 快速,可靠和易于使用\. 默认情况下parses YAML前事,但也支持YAML,JSON,TOML Front-Matter,有设置自定义分隔符的选项\. 用于金属匠、组装、动词和许多其他

### 如何安装 @11ty/gray-matter？

在项目目录运行 npm install @11ty/gray-matter，或使用 pnpm add / yarn add / bun add。

### @11ty/gray-matter 支持 TypeScript 吗？

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

### @11ty/gray-matter 支持 ESM 还是 CommonJS？

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

### @11ty/gray-matter 需要什么版本的 Node\.js？

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

### @11ty/gray-matter 可以商用吗？

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

### @11ty/gray-matter 的下载量有多少？

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

### @11ty/gray-matter 还在维护吗？

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

