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
|
19 | var prettyFormat = require('pretty-format');
|
20 |
|
21 | var obj = { property: {} };
|
22 | obj.circularReference = obj;
|
23 | obj[Symbol('foo')] = 'foo';
|
24 | obj.map = new Map();
|
25 | obj.map.set('prop', 'value');
|
26 | obj.array = [1, NaN, Infinity];
|
27 |
|
28 | console.log(prettyFormat(obj));
|
29 | ```
|
30 |
|
31 | **Result:**
|
32 |
|
33 | ```js
|
34 | Object {
|
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 |
|
55 | Pretty format also supports adding plugins:
|
56 |
|
57 | ```js
|
58 | var 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 |
|
67 | var obj = { foo: { bar: {} } };
|
68 |
|
69 | prettyFormat(obj, {
|
70 | plugins: [fooPlugin]
|
71 | });
|
72 | // Foo: Object {
|
73 | // "bar": Object {}
|
74 | // }
|
75 | ```
|
76 |
|
77 | #### `ReactTestComponent` plugin
|
78 |
|
79 | ```js
|
80 | var prettyFormat = require('pretty-format');
|
81 | var reactPlugin = require('pretty-format/plugins/ReactTestComponent');
|
82 |
|
83 | var React = require('react');
|
84 | var renderer = require('react/lib/ReactTestRenderer');
|
85 |
|
86 | var jsx = React.createElement('h1', null, 'Hello World');
|
87 |
|
88 | prettyFormat(renderer.create(jsx).toJSON(), {
|
89 | plugins: [reactPlugin]
|
90 | });
|
91 | // <h1>
|
92 | // Hello World
|
93 | // </h1>
|
94 | ```
|