Skip to content

Commit 960d905

Browse files
committed
feat: Pass optional stats config to getStats().toJson()
Fixes #18
1 parent 1db2ed9 commit 960d905

File tree

6 files changed

+138
-13
lines changed

6 files changed

+138
-13
lines changed

README.md

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Webpack Stats Plugin
44
[![Build Status][trav_img]][trav_site]
55

66
This plugin will ingest the webpack
7-
[stats](https://github.com/webpack/docs/wiki/node.js-api#stats) object,
7+
[stats](https://webpack.js.org/configuration/stats/#stats) object,
88
process / transform the object and write out to a file for further consumption.
99

1010
The most common use case is building a hashed bundle and wanting to
@@ -41,6 +41,25 @@ module.exports = {
4141
}
4242
```
4343

44+
### Custom `stats` Configuration
45+
46+
This option is passed to the webpack compiler's [`getStats().toJson()`][https://webpack.js.org/api/node/#stats-tojson-options-] method.
47+
48+
```js
49+
const { StatsWriterPlugin } = require("webpack-stats-plugin")
50+
51+
module.exports = {
52+
plugins: [
53+
new StatsWriterPlugin({
54+
stats: {
55+
all: false,
56+
assets: true
57+
}
58+
})
59+
]
60+
}
61+
```
62+
4463
### Custom Transform Function
4564

4665
The transform function has a signature of:
@@ -103,13 +122,14 @@ module.exports = {
103122

104123
### `StatsWriterPlugin(opts)`
105124
* **opts** (`Object`) options
106-
* **opts.filename** (`String`) output file name (Default: "stat.json")
125+
* **opts.filename** (`String`) output file name (Default: "stats.json")
107126
* **opts.fields** (`Array`) fields of stats obj to keep (Default: \["assetsByChunkName"\])
127+
* **opts.stats** (`Object|String`) stats config object or string preset (Default: `{}`)
108128
* **opts.transform** (`Function|Promise`) transform stats obj (Default: `JSON.stringify()`)
109129

110130
Stats writer module.
111131

112-
Stats can be a string or array (we"ll have array from using source maps):
132+
Stats can be a string or array (we'll have an array due to source maps):
113133

114134
```js
115135
"assetsByChunkName": {
@@ -126,9 +146,13 @@ only include those. However, if you want the _whole thing_ (maybe doing an
126146
`opts.transform` function), then you can set `fields: null` in options to
127147
get **all** of the stats object.
128148

149+
You may also pass a custom stats config object (or string preset) via `opts.stats`
150+
in order to select exactly what you want added to the data passed to the transform.
151+
When `opts.stats` is passed, `opts.fields` will default to `null`.
152+
129153
See:
130-
- http://webpack.github.io/docs/long-term-caching.html#get-filenames-from-stats
131-
- https://github.com/webpack/docs/wiki/node.js-api#stats
154+
- https://webpack.js.org/configuration/stats/#stats
155+
- https://webpack.js.org/api/node/#stats-object
132156

133157
**`filename`**: The `opts.filename` option can be a file name or path relative to
134158
`output.path` in webpack configuration. It should not be absolute.

lib/stats-writer-plugin.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const DEFAULT_TRANSFORM = (data) => JSON.stringify(data, null, INDENT);
66
/**
77
* Stats writer module.
88
*
9-
* Stats can be a string or array (we"ll have array from using source maps):
9+
* Stats can be a string or array (we'll have array due to source maps):
1010
*
1111
* ```js
1212
* "assetsByChunkName": {
@@ -23,9 +23,13 @@ const DEFAULT_TRANSFORM = (data) => JSON.stringify(data, null, INDENT);
2323
* `opts.transform` function), then you can set `fields: null` in options to
2424
* get **all** of the stats object.
2525
*
26+
* You may also pass a custom stats config object (or string preset) via `opts.stats`
27+
* in order to select exactly what you want added to the data passed to the transform.
28+
* When `opts.stats` is passed, `opts.fields` will default to `null`.
29+
*
2630
* See:
27-
* - http://webpack.github.io/docs/long-term-caching.html#get-filenames-from-stats
28-
* - https://github.com/webpack/docs/wiki/node.js-api#stats
31+
* - https://webpack.js.org/configuration/stats/#stats
32+
* - https://webpack.js.org/api/node/#stats-object
2933
*
3034
* **`filename`**: The `opts.filename` option can be a file name or path relative to
3135
* `output.path` in webpack configuration. It should not be absolute.
@@ -42,8 +46,9 @@ const DEFAULT_TRANSFORM = (data) => JSON.stringify(data, null, INDENT);
4246
* any problems.
4347
*
4448
* @param {Object} opts options
45-
* @param {String} opts.filename output file name (Default: "stat.json")
49+
* @param {String} opts.filename output file name (Default: "stats.json")
4650
* @param {Array} opts.fields fields of stats obj to keep (Default: \["assetsByChunkName"\])
51+
* @param {Object|String} opts.stats stats config object or string preset (Default: `{}`)
4752
* @param {Function|Promise} opts.transform transform stats obj (Default: `JSON.stringify()`)
4853
*
4954
* @api public
@@ -54,7 +59,13 @@ class StatsWriterPlugin {
5459
this.opts = {};
5560
this.opts.filename = opts.filename || "stats.json";
5661
this.opts.fields = typeof opts.fields !== "undefined" ? opts.fields : ["assetsByChunkName"];
62+
this.opts.stats = opts.stats || {};
5763
this.opts.transform = opts.transform || DEFAULT_TRANSFORM;
64+
65+
if (typeof opts.stats !== "undefined" && typeof opts.fields === "undefined") {
66+
// if custom stats config provided, do not filter fields unless explicitly configured
67+
this.opts.fields = null;
68+
}
5869
}
5970

6071
apply(compiler) {
@@ -67,9 +78,9 @@ class StatsWriterPlugin {
6778

6879
emitStats(curCompiler, callback) {
6980
// Get stats.
70-
// **Note**: In future, could pass something like `{ showAssets: true }`
71-
// to the `getStats()` function for more limited object returned.
72-
let stats = curCompiler.getStats().toJson();
81+
// The second argument automatically skips heavy options (reasons, source, etc)
82+
// if they are otherwise unspecified.
83+
let stats = curCompiler.getStats().toJson(this.opts.stats, "forToString");
7384

7485
// Filter to fields.
7586
if (this.opts.fields) {
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"errors": [],
3+
"warnings": [],
4+
"assets": []
5+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"errors": [],
3+
"warnings": [],
4+
"assetsByChunkName": {
5+
"main": "0fbcc60c464127ab3381.main.js"
6+
},
7+
"assets": []
8+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"errors": [],
3+
"warnings": [],
4+
"chunks": [
5+
{
6+
"rendered": true,
7+
"initial": true,
8+
"entry": true,
9+
"size": 102,
10+
"names": [
11+
"main"
12+
],
13+
"parents": []
14+
}
15+
]
16+
}

test/webpack4/webpack.config.js

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,24 @@
66
const path = require("path");
77
const StatsWriterPlugin = require("../../index").StatsWriterPlugin;
88
const INDENT = 2;
9+
const STAT_RESET = Object.freeze({
10+
// fallback for new stuff added after v3
11+
all: false,
12+
// explicitly turn off older fields
13+
// (webpack <= v2.7.0 does not support "all")
14+
performance: false,
15+
hash: false,
16+
version: false,
17+
timings: false,
18+
entrypoints: false,
19+
chunks: false,
20+
chunkModules: false,
21+
cached: false,
22+
cachedAssets: false,
23+
children: false,
24+
moduleTrace: false,
25+
assets: false
26+
});
927

1028
module.exports = {
1129
mode: "development",
@@ -33,7 +51,7 @@ module.exports = {
3351
transform(data) {
3452
const assetsByChunkName = data.assetsByChunkName;
3553
return Object.keys(assetsByChunkName).reduce((memo, key) => {
36-
return `${memo}${key } | ${ assetsByChunkName[key] }\n`;
54+
return `${memo}${key} | ${assetsByChunkName[key]}\n`;
3755
}, "Name | Asset\n:--- | :----\n");
3856
}
3957
}),
@@ -65,6 +83,49 @@ module.exports = {
6583
main: data.assetsByChunkName.main
6684
}, null, INDENT));
6785
}
86+
}),
87+
// Custom stats
88+
new StatsWriterPlugin({
89+
filename: "stats-custom-stats.json",
90+
stats: Object.assign({}, STAT_RESET, {
91+
assets: true
92+
}),
93+
transform(data) {
94+
// webpack >= v3 adds this field unconditionally, so remove it
95+
delete data.filteredAssets;
96+
return JSON.stringify(data, null, INDENT);
97+
}
98+
}),
99+
new StatsWriterPlugin({
100+
filename: "stats-custom-stats-fields.json",
101+
fields: ["errors", "warnings", "assets"],
102+
stats: Object.assign({}, STAT_RESET, {
103+
assets: true
104+
})
105+
}),
106+
new StatsWriterPlugin({
107+
filename: "stats-override-tostring-opt.json",
108+
stats: Object.assign({}, STAT_RESET, {
109+
// chunks are normally omitted due to second argument of .toJson()
110+
chunks: true
111+
}),
112+
transform(data) {
113+
// normalize subset of chunk metadata across all versions of webpack
114+
data.chunks = data.chunks.map((chunk) => {
115+
return [
116+
"rendered",
117+
"initial",
118+
"entry",
119+
"size",
120+
"names",
121+
"parents"
122+
].reduce((obj, key) => {
123+
obj[key] = chunk[key];
124+
return obj;
125+
}, {});
126+
});
127+
return JSON.stringify(data, null, INDENT);
128+
}
68129
})
69130
]
70131
};

0 commit comments

Comments
 (0)