UNPKG

2.25 kBMarkdownView Raw
1# pretty-format [![Travis build status](http://img.shields.io/travis/thejameskyle/pretty-format.svg?style=flat)](https://travis-ci.org/thejameskyle/pretty-format)
2
3> Stringify any JavaScript value.
4
5- Supports [all built-in JavaScript types](#type-support)
6- [Blazingly fast](https://gist.github.com/thejameskyle/2b04ffe4941aafa8f970de077843a8fd) (similar performance to v8's `JSON.stringify` and significantly faster than Node's `util.format`)
7- Plugin system for extending with custom types (i.e. [`ReactTestComponent`](#reacttestcomponent-plugin))
8
9
10## Installation
11
12```sh
13$ npm install pretty-format
14```
15
16## Usage
17
18```js
19var prettyFormat = require('pretty-format');
20
21var obj = { property: {} };
22obj.circularReference = obj;
23obj[Symbol('foo')] = 'foo';
24obj.map = new Map();
25obj.map.set('prop', 'value');
26obj.array = [1, NaN, Infinity];
27
28console.log(prettyFormat(obj));
29```
30
31**Result:**
32
33```js
34Object {
35 "property": Object {},
36 "circularReference": [Circular],
37 "map": Map {
38 "prop" => "value"
39 },
40 "array": Array [
41 1,
42 NaN,
43 Infinity
44 ],
45 Symbol(foo): "foo"
46}
47```
48
49#### Type Support
50
51`Object`, `Array`, `ArrayBuffer`, `DataView`, `Float32Array`, `Float64Array`, `Int8Array`, `Int16Array`, `Int32Array`, `Uint8Array`, `Uint8ClampedArray`, `Uint16Array`, `Uint32Array`, `arguments`, `Boolean`, `Date`, `Error`, `Function`, `Infinity`, `Map`, `NaN`, `null`, `Number`, `RegExp`, `Set`, `String`, `Symbol`, `undefined`, `WeakMap`, `WeakSet`
52
53### Plugins
54
55Pretty format also supports adding plugins:
56
57```js
58var fooPlugin = {
59 test: function(val) {
60 return val && val.hasOwnProperty('foo');
61 },
62 print: function(val, print, indent) {
63 return 'Foo: ' + print(val.foo);
64 }
65};
66
67var obj = { foo: { bar: {} } };
68
69prettyFormat(obj, {
70 plugins: [fooPlugin]
71});
72// Foo: Object {
73// "bar": Object {}
74// }
75```
76
77#### `ReactTestComponent` plugin
78
79```js
80var prettyFormat = require('pretty-format');
81var reactPlugin = require('pretty-format/plugins/ReactTestComponent');
82
83var React = require('react');
84var renderer = require('react/lib/ReactTestRenderer');
85
86var jsx = React.createElement('h1', null, 'Hello World');
87
88prettyFormat(renderer.create(jsx).toJSON(), {
89 plugins: [reactPlugin]
90});
91// <h1>
92// Hello World
93// </h1>
94```