@rollup-extras/plugin-size 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Konstantin Shutkin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @rollup-extras/plugin-size
2
+
3
+ Rollup plugin that reports the size of generated artifacts — raw, minified (via [oxc-minify](https://www.npmjs.com/package/oxc-minify)), and compressed (gzip and/or brotli).
4
+
5
+ Output is summarised by category:
6
+
7
+ | Category | Grouping | Sizes shown |
8
+ | -------------------- | ------------------------------------- | ------------------------------ |
9
+ | **Entry chunks** | output format (`es`, `cjs`, `umd`, …) | raw → minified → gzip / brotli |
10
+ | **Non-entry chunks** | output format | raw → minified → gzip / brotli |
11
+ | **Assets** | file extension (`.css`, `.svg`, …) | raw → gzip / brotli |
12
+
13
+ A JSON stats file is maintained between builds so that size deltas are printed on subsequent runs. Only categories that appear in either the current or the previous build are shown — nothing irrelevant is printed.
14
+
15
+ ## Installation
16
+
17
+ Using npm:
18
+
19
+ ```
20
+ npm install --save-dev @rollup-extras/plugin-size
21
+ ```
22
+
23
+ Using pnpm:
24
+
25
+ ```
26
+ pnpm add -D @rollup-extras/plugin-size
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ### Minimal
32
+
33
+ ```js
34
+ import size from "@rollup-extras/plugin-size";
35
+
36
+ export default {
37
+ input: "src/index.js",
38
+ output: {
39
+ dir: "dist",
40
+ format: "es",
41
+ },
42
+ plugins: [size()],
43
+ };
44
+ ```
45
+
46
+ ### Custom stats file path
47
+
48
+ ```js
49
+ size({ statsFile: "build/.size-stats.json" });
50
+ ```
51
+
52
+ ### Disable stats file update (report-only)
53
+
54
+ ```js
55
+ size({ updateStats: false });
56
+ ```
57
+
58
+ ### Enable brotli reporting
59
+
60
+ ```js
61
+ size({ brotli: true });
62
+ ```
63
+
64
+ ### Brotli only (no gzip)
65
+
66
+ ```js
67
+ size({ gzip: false, brotli: true });
68
+ ```
69
+
70
+ ### Full options
71
+
72
+ ```js
73
+ size({
74
+ statsFile: ".stats.json",
75
+ updateStats: true,
76
+ gzip: true,
77
+ brotli: true,
78
+ pluginName: "my-size",
79
+ });
80
+ ```
81
+
82
+ ## Options
83
+
84
+ | Option | Type | Default | Description |
85
+ | ------------- | --------- | ------------------------------ | ------------------------------------------------------------------- |
86
+ | `statsFile` | `string` | `'.stats.json'` | Path to the JSON stats file (relative to project root or absolute). |
87
+ | `updateStats` | `boolean` | `true` | Whether to overwrite the stats file with the current build data. |
88
+ | `gzip` | `boolean` | `true` | Report gzip-compressed sizes. |
89
+ | `brotli` | `boolean` | `false` | Report brotli-compressed sizes. |
90
+ | `pluginName` | `string` | `'@rollup-extras/plugin-size'` | Override the plugin name reported to Rollup. |
91
+
92
+ ## How it works
93
+
94
+ The plugin hooks into Rollup's `generateBundle` and `closeBundle` lifecycle:
95
+
96
+ 1. **`generateBundle`** — iterates over every chunk and asset in the output bundle.
97
+ - **Chunks** (entry and non-entry) are minified with `oxc-minify` and then compressed with the enabled algorithms (gzip and/or brotli). Sizes are accumulated per output format.
98
+ - **Assets** are compressed with the enabled algorithms (no JS minification). Sizes are accumulated per file extension.
99
+ 2. **`closeBundle`** (via `multiConfigPluginBase`) — loads the previous stats file (if any), prints a comparison report using [`@niceties/ansi`](https://www.npmjs.com/package/@niceties/ansi) colours, and writes the updated stats file.
100
+
101
+ Size deltas are colour-coded: **green** for decreases, **red** for increases, and dim for no change. Categories that existed in the previous build but are absent in the current one are reported as _removed_.
102
+
103
+ ## License
104
+
105
+ [MIT](https://github.com/kshutkin/rollup-extras/blob/main/LICENSE)
package/index.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ declare module '@rollup-extras/plugin-size' {
2
+ import type { Plugin } from 'rollup';
3
+ /**
4
+ * Rollup plugin that reports the size of generated artifacts.
5
+ *
6
+ * Chunks are minified with oxc-minify and then compressed with gzip and / or
7
+ * brotli to produce the reported sizes. Assets are compressed only (no JS
8
+ * minification). Results are compared against a persisted JSON stats file so
9
+ * that size regressions are easy to spot.
10
+ *
11
+ * */
12
+ export default function _default(options?: SizePluginOptions): Plugin & {
13
+ api: {
14
+ addInstance(): Plugin;
15
+ };
16
+ };
17
+ export type SizePluginOptions = {
18
+ pluginName?: string;
19
+ statsFile?: string;
20
+ updateStats?: boolean;
21
+ gzip?: boolean;
22
+ brotli?: boolean;
23
+ };
24
+ export type ChunkSizeStats = {
25
+ raw: number;
26
+ minified: number;
27
+ gzip?: number;
28
+ brotli?: number;
29
+ };
30
+ export type AssetSizeStats = {
31
+ raw: number;
32
+ gzip?: number;
33
+ brotli?: number;
34
+ };
35
+ export type StatsData = {
36
+ entries?: Record<string, ChunkSizeStats>;
37
+ chunks?: Record<string, ChunkSizeStats>;
38
+ assets?: Record<string, AssetSizeStats>;
39
+ };
40
+ export type CompressionFlags = {
41
+ gzip: boolean;
42
+ brotli: boolean;
43
+ };
44
+
45
+ export {};
46
+ }
47
+
48
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "version": 3,
3
+ "file": "index.d.ts",
4
+ "names": [
5
+ "SizePluginOptions",
6
+ "ChunkSizeStats",
7
+ "AssetSizeStats",
8
+ "StatsData",
9
+ "CompressionFlags"
10
+ ],
11
+ "sources": [
12
+ "index.js"
13
+ ],
14
+ "sourcesContent": [
15
+ null
16
+ ],
17
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
18
+ "ignoreList": []
19
+ }
package/index.js ADDED
@@ -0,0 +1,219 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { extname, resolve } from 'node:path';
3
+ import { promisify } from 'node:util';
4
+ import { brotliCompress as brotliCb, gzip as gzipCb } from 'node:zlib';
5
+
6
+ import { minify } from 'oxc-minify';
7
+
8
+ import { bold, cyan, dim, green, red, yellow } from '@niceties/ansi';
9
+ import logger from '@rollup-extras/utils/logger';
10
+ import { multiConfigPluginBase } from '@rollup-extras/utils/multi-config-plugin-base';
11
+ import { getOptionsObject } from '@rollup-extras/utils/options';
12
+
13
+ const gzip = promisify(gzipCb);
14
+ const brotli = promisify(brotliCb);
15
+
16
+ const factories = { logger };
17
+
18
+ function formatSize(bytes) {
19
+ if (bytes < 1024) return `${bytes} B`;
20
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} kB`;
21
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
22
+ }
23
+
24
+ function formatDelta(current, previous) {
25
+ if (previous == null) return '';
26
+ const delta = current - previous;
27
+ if (delta === 0) return dim(' (=)');
28
+ if (delta > 0) return red(` (+${formatSize(delta)})`);
29
+ return green(` (-${formatSize(Math.abs(delta))})`);
30
+ }
31
+
32
+ function formatCompressed(cur, prev) {
33
+ const parts = [];
34
+ if (cur.gzip != null) {
35
+ parts.push(`${bold(formatSize(cur.gzip))} gzip${formatDelta(cur.gzip, prev?.gzip)}`);
36
+ }
37
+ if (cur.brotli != null) {
38
+ parts.push(`${bold(formatSize(cur.brotli))} brotli${formatDelta(cur.brotli, prev?.brotli)}`);
39
+ }
40
+ if (parts.length === 0) return '';
41
+ return ` → ${parts.join(' / ')}`;
42
+ }
43
+
44
+ function allKeys(a, b) {
45
+ const set = new Set([...Object.keys(a || {}), ...Object.keys(b || {})]);
46
+ return [...set].sort();
47
+ }
48
+
49
+ function printReport(current, previous, log) {
50
+ const entryKeys = allKeys(current.entries, previous.entries);
51
+ const chunkKeys = allKeys(current.chunks, previous.chunks);
52
+ const assetKeys = allKeys(current.assets, previous.assets);
53
+
54
+ if (entryKeys.length === 0 && chunkKeys.length === 0 && assetKeys.length === 0) {
55
+ return;
56
+ }
57
+
58
+ for (const format of entryKeys) {
59
+ const cur = current.entries?.[format];
60
+ const prev = previous.entries?.[format];
61
+ if (cur) {
62
+ log(`${bold(cyan(format))} entry: ${formatSize(cur.raw)} → ${formatSize(cur.minified)}${formatCompressed(cur, prev)}`);
63
+ } else {
64
+ log(`${bold(cyan(format))} entry: ${dim('removed')}`);
65
+ }
66
+ }
67
+
68
+ for (const format of chunkKeys) {
69
+ const cur = current.chunks?.[format];
70
+ const prev = previous.chunks?.[format];
71
+ if (cur) {
72
+ log(`${bold(cyan(format))} chunks: ${formatSize(cur.raw)} → ${formatSize(cur.minified)}${formatCompressed(cur, prev)}`);
73
+ } else {
74
+ log(`${bold(cyan(format))} chunks: ${dim('removed')}`);
75
+ }
76
+ }
77
+
78
+ for (const ext of assetKeys) {
79
+ const cur = current.assets?.[ext];
80
+ const prev = previous.assets?.[ext];
81
+ if (cur) {
82
+ log(`${bold(yellow(ext))} assets: ${formatSize(cur.raw)}${formatCompressed(cur, prev)}`);
83
+ } else {
84
+ log(`${bold(yellow(ext))} assets: ${dim('removed')}`);
85
+ }
86
+ }
87
+ }
88
+
89
+ async function compressSizes(buf, flags) {
90
+
91
+ const result = {};
92
+
93
+ const tasks = [];
94
+
95
+ if (flags.gzip) {
96
+ tasks.push(
97
+ gzip(buf).then(compressed => {
98
+ result.gzip = compressed.byteLength;
99
+ })
100
+ );
101
+ }
102
+ if (flags.brotli) {
103
+ tasks.push(
104
+ brotli(buf).then(compressed => {
105
+ result.brotli = compressed.byteLength;
106
+ })
107
+ );
108
+ }
109
+
110
+ await Promise.all(tasks);
111
+ return result;
112
+ }
113
+
114
+ async function collectStats(currentStats, outputOptions, bundle, flags) {
115
+ const format = outputOptions.format;
116
+
117
+ await Promise.all(
118
+ Object.entries(bundle).map(async ([fileName, item]) => {
119
+ if (item.type === 'chunk') {
120
+ const code = (item).code;
121
+ const raw = Buffer.byteLength(code, 'utf8');
122
+
123
+ const minResult = await minify(fileName, code, {
124
+ compress: { target: 'esnext' },
125
+ mangle: { toplevel: true },
126
+ codegen: { removeWhitespace: true },
127
+ });
128
+ const minifiedSize = Buffer.byteLength(minResult.code, 'utf8');
129
+ const sizes = await compressSizes(Buffer.from(minResult.code, 'utf8'), flags);
130
+
131
+ const category = (item).isEntry ? 'entries' : 'chunks';
132
+ if (!currentStats[category]) {
133
+ currentStats[category] = {};
134
+ }
135
+ const bucket = (currentStats[category]);
136
+ if (!bucket[format]) {
137
+ bucket[format] = { raw: 0, minified: 0 };
138
+ }
139
+ bucket[format].raw += raw;
140
+ bucket[format].minified += minifiedSize;
141
+ if (sizes.gzip != null) {
142
+ bucket[format].gzip = (bucket[format].gzip ?? 0) + sizes.gzip;
143
+ }
144
+ if (sizes.brotli != null) {
145
+ bucket[format].brotli = (bucket[format].brotli ?? 0) + sizes.brotli;
146
+ }
147
+ } else {
148
+ const source = (item).source;
149
+ const raw = typeof source === 'string' ? Buffer.byteLength(source, 'utf8') : source.byteLength;
150
+ const ext = extname(fileName) || fileName;
151
+ const buf = typeof source === 'string' ? Buffer.from(source, 'utf8') : Buffer.from(source);
152
+ const sizes = await compressSizes(buf, flags);
153
+
154
+ if (!currentStats.assets) {
155
+ currentStats.assets = {};
156
+ }
157
+ if (!currentStats.assets[ext]) {
158
+ currentStats.assets[ext] = { raw: 0 };
159
+ }
160
+ currentStats.assets[ext].raw += raw;
161
+ if (sizes.gzip != null) {
162
+ currentStats.assets[ext].gzip = (currentStats.assets[ext].gzip ?? 0) + sizes.gzip;
163
+ }
164
+ if (sizes.brotli != null) {
165
+ currentStats.assets[ext].brotli = (currentStats.assets[ext].brotli ?? 0) + sizes.brotli;
166
+ }
167
+ }
168
+ })
169
+ );
170
+ }
171
+
172
+ async function loadPreviousStats(statsPath) {
173
+ try {
174
+ const content = await readFile(statsPath, 'utf8');
175
+ return JSON.parse(content);
176
+ } catch {
177
+ return {};
178
+ }
179
+ }
180
+
181
+ export default function (options) {
182
+ const normalizedOptions = getOptionsObject(
183
+ options ?? {},
184
+ {
185
+ pluginName: '@rollup-extras/plugin-size',
186
+ statsFile: '.stats.json',
187
+ updateStats: true,
188
+ gzip: true,
189
+ brotli: false,
190
+ },
191
+ factories
192
+ );
193
+
194
+ const { pluginName, statsFile, updateStats, logger } = normalizedOptions;
195
+
196
+ const flags = { gzip: normalizedOptions.gzip, brotli: normalizedOptions.brotli };
197
+
198
+ const currentStats = {};
199
+
200
+ const instance = multiConfigPluginBase(false, pluginName, reportAndSave, onEachOutput);
201
+
202
+ return instance;
203
+
204
+ async function onEachOutput(outputOptions, bundle) {
205
+ await collectStats(currentStats, outputOptions, bundle, flags);
206
+ }
207
+
208
+ async function reportAndSave() {
209
+ const statsPath = resolve(process.cwd(), statsFile);
210
+
211
+ const previousStats = await loadPreviousStats(statsPath);
212
+
213
+ printReport(currentStats, previousStats, logger);
214
+
215
+ if (updateStats) {
216
+ await writeFile(statsPath, `${JSON.stringify(currentStats, null, 2)}\n`);
217
+ }
218
+ }
219
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "license": "MIT",
4
+ "name": "@rollup-extras/plugin-size",
5
+ "author": "Konstantin Shutkin",
6
+ "type": "module",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "main": "./index.js",
16
+ "module": "./index.js",
17
+ "engines": {
18
+ "node": ">=15"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/kshutkin/rollup-extras.git",
23
+ "directory": "plugin-size"
24
+ },
25
+ "bugs": "https://github.com/kshutkin/rollup-extras/issues",
26
+ "homepage": "https://github.com/kshutkin/rollup-extras/blob/main/plugin-size/README.md",
27
+ "readme": "README.md",
28
+ "description": "Rollup plugin to report the size of generated artifacts (raw, minified, gzip).",
29
+ "keywords": [
30
+ "rollup-plugin",
31
+ "size",
32
+ "bundle-size",
33
+ "gzip",
34
+ "minify",
35
+ "report"
36
+ ],
37
+ "dependencies": {
38
+ "@niceties/ansi": "^1.1.2",
39
+ "@niceties/logger": "^2.1.0",
40
+ "oxc-minify": "^0.125.0",
41
+ "@rollup-extras/utils": "^2.0.0"
42
+ },
43
+ "peerDependencies": {
44
+ "rollup": "^4.0.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "rollup": {
48
+ "optional": true
49
+ }
50
+ }
51
+ }