pretty-format

中文文档
30.5.1发布于 2026/09/01MITTypeScriptESM + CJS近 30 天下载 9.2亿

字符串化任何JavaScript值。

中文使用文档
文档目录12 节
  1. 安装
  2. 用法
  3. 与选项一起使用
  4. 插件用法
  5. 笑话用法
  6. 编写插件
  7. 测试
  8. 序列化
  9. 配置
  10. 序列化和测试的示例
  11. 打印
  12. 打印和测试的示例

格式

字符串化任何JavaScript值。

  • 序列化内置JavaScript类型。
  • 使用内置或用户定义的插件序列化特定于应用程序的数据类型。

安装

$ yarn add pretty-format

用法

const {format: prettyFormat} = require('pretty-format'); // CommonJS
import {format as prettyFormat} from 'pretty-format'; // ES2015 modules
const val = {object: {}};
val.circularReference = val;
val[Symbol('foo')] = 'foo';
val.map = new Map([['prop', 'value']]);
val.array = [-0, Infinity, NaN];

console.log(prettyFormat(val));
/*
Object {
  "array": Array [
    -0,
    Infinity,
    NaN,
  ],
  "circularReference": [Circular],
  "map": Map {
    "prop" => "value",
  },
  "object": Object {},
  Symbol(foo): "foo",
}
*/

与选项一起使用

function onClick() {}

console.log(prettyFormat(onClick));
/*
[Function onClick]
*/

const options = {
  printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
关键类型默认的描述
callToJSONbooleantrue呼叫 toJSON 方法(如果存在)
compareKeysfunction|nullundefined排序对象键时使用的比较函数, null 可以用来跳过排序吗
escapeRegexbooleanfalse正则表达式中的特殊字符转义
escapeStringbooleantrue转义字符串中的特殊字符
highlightbooleanfalse在终端用颜色高亮语法(一些插件)
indentnumber2每层缩进中的空格
maxDepthnumberInfinity要在数组、对象、元素等中打印的级别
maxWidthnumberInfinity要在数组、集合等中打印的元素数目
minbooleanfalse尽量减少增加的空间:没有缩进和换行
pluginsarray[]用于序列化应用程序特定数据类型的插件
printBasicPrototypebooleanfalse打印普通对象和数组的原型
printFunctionNamebooleantrue包括或省略函数名
themeobject在终端中突出显示语法的颜色

的属性值 theme 来自 ansi-styles颜色

const DEFAULT_THEME = {
  comment: 'gray',
  content: 'reset',
  prop: 'yellow',
  tag: 'cyan',
  value: 'green',
};

插件用法

这个 pretty-format 包提供了一些内置插件,包括:

  • ReactElement 的元素 react
  • ReactTestComponent 的测试对象 react-test-renderer (弃用)
// CommonJS
const React = require('react');
const renderer = require('react-test-renderer');
const {format: prettyFormat, plugins} = require('pretty-format');

const {ReactElement, ReactTestComponent} = plugins;
// ES2015 modules and destructuring assignment
import React from 'react';
import renderer from 'react-test-renderer';
import {plugins, format as prettyFormat} from 'pretty-format';

const {ReactElement, ReactTestComponent} = plugins;
const onClick = () => {};
const element = React.createElement('button', {onClick}, 'Hello World');

const formatted1 = prettyFormat(element, {
  plugins: [ReactElement],
  printFunctionName: false,
});
const formatted2 = prettyFormat(renderer.create(element).toJSON(), {
  plugins: [ReactTestComponent],
  printFunctionName: false,
});
/*
<button
  onClick=[Function]
>
  Hello World
</button>
*/

笑话用法

对于快照测试,Jest使用 pretty-format 与选项,包括一些内置的插件。为此,插件也被称为 快照序列化器。

要序列化特定于应用程序的数据类型,可以将模块添加到 devDependencies 一个项目,然后:

在一个 个人 测试文件中,可以添加如下模块。它位于Jest配置中的任何模块之前。

import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);

// tests which have `expect(value).toMatchSnapshot()` assertions

为 所有 测试文件,您可以在Jest配置中指定模块。它们位于React、HTML和Immutable.js数据类型的内置插件之前。例如,在a package.json 文件:

{
  "jest": {
    "snapshotSerializers": ["my-serializer-module"]
  }
}

编写插件

插件是一个JavaScript对象。

如果 options 有一个 plugins 数组:用于第一个插件 test(val) 方法返回真值 prettyFormat(val, options) 返回下列任一操作的结果:

  • serialize(val, …) 方法 改进的 接口(可在 版本21 或更高版本)
  • print(val, …) 方法 原始 接口(如果插件没有) serialize 方法)

测试

写 test 所以它可以接收 val 任何类型的参数。序列化 对象 哪一个有一定的属性,那么一个谨慎的表达就像 val != null && … 或者更简洁一点 val && … 防止以下错误:

  • TypeError: Cannot read property 'whatever' of null
  • TypeError: Cannot read property 'whatever' of undefined

例如, test 内置法 ReactElement 插件:

const elementSymbol = Symbol.for('react.element');
const test = val => val && val.$$typeof === elementSymbol;

注意效率 test 因为 pretty-format 经常打电话。

序列化

这个 改进的 接口在 版本21 或更高版本。

写 serialize 给定参数,返回一个字符串:

  • val “通过了考验”
  • 不变的 config 对象:来源于 options
  • 当前的 indentation 字符串:连接到 indent 从 config
  • 当前的 depth 数字:与…相比 maxDepth 从 config
  • 当前的 refs 数组:查找对象中的循环引用
  • printer 回调函数:序列化子函数

配置

关键类型描述
callToJSONboolean呼叫 toJSON 方法(如果存在)
compareKeysfunction|null排序对象键时使用的比较函数, null 可以用来跳过排序吗
colorsObject用于突出显示语法的颜色的转义码
escapeRegexboolean正则表达式中的特殊字符转义
escapeStringboolean转义字符串中的特殊字符
indentstring每层缩进中的空格
maxDepthnumber要在数组、对象、元素等中打印的级别
minboolean尽量减少增加的空间:没有缩进和换行
pluginsarray用于序列化应用程序特定数据类型的插件
printFunctionNameboolean包括或省略函数名
spacingInnerstring分隔列表中项目的空格
spacingOuterstring包含项目列表的空格

的每个性质 colors 在 config 对应于的性质 theme 在 options:

  • 关键是一样的(例如, tag)
  • 的值 colors 是一个对象 open 和 close 其值为转义码的属性 ansi-styles 的颜色值 theme (例如, 'cyan')

中的一些属性 config 来源于 min 在 options:

  • spacingInner 和 spacingOuter 是 换行符 如果 min 是 false
  • spacingInner 是 空间 和 spacingOuter 是 空字符串 如果 min 是 true

序列化和测试的示例

这个插件是一个模式,您可以应用它来序列化复合数据类型。注: pretty-format 不需要插件来序列化数组。

// We reused more code when we factored out a function for child items
// that is independent of depth, name, and enclosing punctuation (see below).
const SEPARATOR = ',';
function serializeItems(items, config, indentation, depth, refs, printer) {
  if (items.length === 0) {
    return '';
  }
  const indentationItems = indentation + config.indent;
  return (
    config.spacingOuter +
    items
      .map(
        item =>
          indentationItems +
          printer(item, config, indentationItems, depth, refs), // callback
      )
      .join(SEPARATOR + config.spacingInner) +
    (config.min ? '' : SEPARATOR) + // following the last item
    config.spacingOuter +
    indentation
  );
}

const plugin = {
  test(val) {
    return Array.isArray(val);
  },
  serialize(array, config, indentation, depth, refs, printer) {
    const name = array.constructor.name;
    return ++depth > config.maxDepth
      ? `[${name}]`
      : `${config.min ? '' : `${name} `}[${serializeItems(
          array,
          config,
          indentation,
          depth,
          refs,
          printer,
        )}]`;
  },
};
const val = {
  filter: 'completed',
  items: [
    {
      text: 'Write test',
      completed: true,
    },
    {
      text: 'Write serialize',
      completed: true,
    },
  ],
};
console.log(
  prettyFormat(val, {
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": Array [
    Object {
      "completed": true,
      "text": "Write test",
    },
    Object {
      "completed": true,
      "text": "Write serialize",
    },
  ],
}
*/
console.log(
  prettyFormat(val, {
    indent: 4,
    plugins: [plugin],
  }),
);
/*
Object {
    "filter": "completed",
    "items": Array [
        Object {
            "completed": true,
            "text": "Write test",
        },
        Object {
            "completed": true,
            "text": "Write serialize",
        },
    ],
}
*/
console.log(
  prettyFormat(val, {
    maxDepth: 1,
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": [Array],
}
*/
console.log(
  prettyFormat(val, {
    min: true,
    plugins: [plugin],
  }),
);
/*
{"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
*/

打印

这个 原始 接口是足够的插件:

  • 那 不 依赖于其他选项 highlight 或 min
  • 那 不 取决于 depth 或 refs 在递归遍历中,和
  • If值任选其一
    • 做。 不 要求缩进,或
    • 做。 不 作为JavaScript数据结构(例如,数组)的子元素出现

写 print 给定参数,返回一个字符串:

  • val “通过了考验”
  • 当前的 printer(valChild) 回调函数:序列化子函数
  • 当前的 indenter(lines) 回调函数:在下一层缩进行
  • 不变的 config 对象:来源于 options
  • 不变的 colors 对象:来源于 options

的三个性质 config 是 min 在 options 和:

  • spacing 和 edgeSpacing 是 换行符 如果 min 是 false
  • spacing 是 空间 和 edgeSpacing 是 空字符串 如果 min 是 true

的每个性质 colors 对应于的性质 theme 在 options:

  • 关键是一样的(例如, tag)
  • 的值 colors 是一个对象 open 和 close 其值为转义码的属性 ansi-styles 的颜色值 theme (例如, 'cyan')

打印和测试的示例

这个插件使用 命名参数的数量 不包括rest参数。

const plugin = {
  print(val) {
    return `[Function ${val.name || 'anonymous'} ${val.length}]`;
  },
  test(val) {
    return typeof val === 'function';
  },
};
const val = {
  onClick(event) {},
  render() {},
};

prettyFormat(val, {
  plugins: [plugin],
});
/*
Object {
  "onClick": [Function onClick 1],
  "render": [Function render 0],
}
*/

prettyFormat(val);
/*
Object {
  "onClick": [Function onClick],
  "render": [Function render],
}
*/

这个插件 忽略了 这个 printFunctionName 选择。原来的限制 print 界面是使用改进的一个原因 serialize 接口,如上所述。

prettyFormat(val, {
  plugins: [pluginOld],
  printFunctionName: false,
});
/*
Object {
  "onClick": [Function onClick 1],
  "render": [Function render 0],
}
*/

prettyFormat(val, {
  printFunctionName: false,
});
/*
Object {
  "onClick": [Function],
  "render": [Function],
}
*/

版本与发布记录

pretty-format 共发布 253 个版本,首次发布于 2015/03/08;过去 12 个月发布了 5 个版本。

版本发布日期距今
30.5.1latest2026/09/012 个月前
30.5.02026/08/282 个月前
30.4.12026/05/085 个月前
30.4.02026/05/085 个月前
30.3.02026/03/107 个月前
30.2.02025/09/281.1 年前

其他发布通道:next → 30.0.0-rc.1。

关于 pretty-format 的常见问题

pretty-format 是什么?

字符串化任何JavaScript值。

如何安装 pretty-format?

在项目目录运行 npm install pretty-format,或使用 pnpm add / yarn add / bun add。

pretty-format 支持 TypeScript 吗?

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

pretty-format 支持 ESM 还是 CommonJS?

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

pretty-format 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

pretty-format 可以商用吗?

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

pretty-format 的下载量有多少?

根据 npm 官方下载统计,pretty-format 在 2026/10/05 – 2026/11/03 这 30 天内被下载 918,698,082 次,日均约 30,623,269 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

pretty-format 还在维护吗?

最新版本 30.5.1 发布于 2026/09/01(2 个月前);至今共发布 253 个版本,其中过去 12 个月发布了 5 个;首次发布于 2015/03/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。