pretty-format

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

Stringify any JavaScript value.

原始使用文档
文档目录12 节
  1. Installation
  2. Usage
  3. Usage with options
  4. Usage with plugins
  5. Usage in Jest
  6. Writing plugins
  7. test
  8. serialize
  9. config
  10. Example of serialize and test
  11. print
  12. Example of print and test

pretty-format

Stringify any JavaScript value.

  • Serialize built-in JavaScript types.
  • Serialize application-specific data types with built-in or user-defined plugins.

Installation

$ yarn add pretty-format

Usage

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",
}
*/

Usage with options

function onClick() {}

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

const options = {
  printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
keytypedefaultdescription
callToJSONbooleantruecall toJSON method (if it exists) on objects
compareKeysfunction|nullundefinedcompare function used when sorting object keys, null can be used to skip over sorting
escapeRegexbooleanfalseescape special characters in regular expressions
escapeStringbooleantrueescape special characters in strings
highlightbooleanfalsehighlight syntax with colors in terminal (some plugins)
indentnumber2spaces in each level of indentation
maxDepthnumberInfinitylevels to print in arrays, objects, elements, and so on
maxWidthnumberInfinitynumber of elements to print in arrays, sets, and so on
minbooleanfalseminimize added space: no indentation nor line breaks
pluginsarray[]plugins to serialize application-specific data types
printBasicPrototypebooleanfalseprint the prototype for plain objects and arrays
printFunctionNamebooleantrueinclude or omit the name of a function
themeobjectcolors to highlight syntax in terminal

Property values of theme are from ansi-styles colors

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

Usage with plugins

The pretty-format package provides some built-in plugins, including:

  • ReactElement for elements from react
  • ReactTestComponent for test objects from react-test-renderer (deprecated)
// 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>
*/

Usage in Jest

For snapshot tests, Jest uses pretty-format with options that include some of its built-in plugins. For this purpose, plugins are also known as snapshot serializers.

To serialize application-specific data types, you can add modules to devDependencies of a project, and then:

In an individual test file, you can add a module as follows. It precedes any modules from Jest configuration.

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

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

For all test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a package.json file:

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

Writing plugins

A plugin is a JavaScript object.

If options has a plugins array: for the first plugin whose test(val) method returns a truthy value, then prettyFormat(val, options) returns the result from either:

  • serialize(val, …) method of the improved interface (available in version 21 or later)
  • print(val, …) method of the original interface (if plugin does not have serialize method)

test

Write test so it can receive val argument of any type. To serialize objects which have certain properties, then a guarded expression like val != null && … or more concise val && … prevents the following errors:

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

For example, test method of built-in ReactElement plugin:

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

Pay attention to efficiency in test because pretty-format calls it often.

serialize

The improved interface is available in version 21 or later.

Write serialize to return a string, given the arguments:

  • val which “passed the test”
  • unchanging config object: derived from options
  • current indentation string: concatenate to indent from config
  • current depth number: compare to maxDepth from config
  • current refs array: find circular references in objects
  • printer callback function: serialize children

config

keytypedescription
callToJSONbooleancall toJSON method (if it exists) on objects
compareKeysfunction|nullcompare function used when sorting object keys, null can be used to skip over sorting
colorsObjectescape codes for colors to highlight syntax
escapeRegexbooleanescape special characters in regular expressions
escapeStringbooleanescape special characters in strings
indentstringspaces in each level of indentation
maxDepthnumberlevels to print in arrays, objects, elements, and so on
minbooleanminimize added space: no indentation nor line breaks
pluginsarrayplugins to serialize application-specific data types
printFunctionNamebooleaninclude or omit the name of a function
spacingInnerstringspacing to separate items in a list
spacingOuterstringspacing to enclose a list of items

Each property of colors in config corresponds to a property of theme in options:

  • the key is the same (for example, tag)
  • the value in colors is a object with open and close properties whose values are escape codes from ansi-styles for the color value in theme (for example, 'cyan')

Some properties in config are derived from min in options:

  • spacingInner and spacingOuter are newline if min is false
  • spacingInner is space and spacingOuter is empty string if min is true

Example of serialize and test

This plugin is a pattern you can apply to serialize composite data types. Side note: pretty-format does not need a plugin to serialize arrays.

// 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"}]}
*/

print

The original interface is adequate for plugins:

  • that do not depend on options other than highlight or min
  • that do not depend on depth or refs in recursive traversal, and
  • if values either
    • do not require indentation, or
    • do not occur as children of JavaScript data structures (for example, array)

Write print to return a string, given the arguments:

  • val which “passed the test”
  • current printer(valChild) callback function: serialize children
  • current indenter(lines) callback function: indent lines at the next level
  • unchanging config object: derived from options
  • unchanging colors object: derived from options

The 3 properties of config are min in options and:

  • spacing and edgeSpacing are newline if min is false
  • spacing is space and edgeSpacing is empty string if min is true

Each property of colors corresponds to a property of theme in options:

  • the key is the same (for example, tag)
  • the value in colors is a object with open and close properties whose values are escape codes from ansi-styles for the color value in theme (for example, 'cyan')

Example of print and test

This plugin prints functions with the number of named arguments excluding rest argument.

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],
}
*/

This plugin ignores the printFunctionName option. That limitation of the original print interface is a reason to use the improved serialize interface, described above.

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 是什么?

Stringify any JavaScript value.

如何安装 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 和提交记录判断。