1 | const { error, message } = require("simple-output");
|
2 | const { resolve } = require("path");
|
3 | const { writeFileSync, readFileSync, existsSync } = require("fs");
|
4 | const pkg = require(`${process.cwd()}/package`);
|
5 | const log = require("./utils/log");
|
6 |
|
7 | const sizeSnapshotPath = resolve(".size-snapshot.json");
|
8 | const units = ["B", "kB", "MB", "GB"];
|
9 |
|
10 | function convertSize(size, unitIterator, lastUnitValue) {
|
11 | const unit = unitIterator.next();
|
12 |
|
13 | return size >= 1024 && !unit.done
|
14 | ? convertSize(Math.round((size / 1024) * 100) / 100, unitIterator, lastUnitValue)
|
15 | : `${size} ${unit.value || lastUnitValue}`;
|
16 | }
|
17 |
|
18 | (async function main() {
|
19 | if (existsSync(sizeSnapshotPath)) {
|
20 | message(`Start build size conversion. Parse ${sizeSnapshotPath}`);
|
21 |
|
22 | const sizeJson = JSON.parse(readFileSync(sizeSnapshotPath));
|
23 | const sizeKey = Object.keys(sizeJson).find((key) => /\.cjs\.js$/.test(key));
|
24 |
|
25 | await log(async () => {
|
26 | sizeJson.module = convertSize(
|
27 | sizeJson[sizeKey].gzipped,
|
28 | units.values(),
|
29 | units[units.length - 1]
|
30 | );
|
31 | return "Convert module size";
|
32 | });
|
33 |
|
34 | await log(async () => {
|
35 | writeFileSync(sizeSnapshotPath, JSON.stringify(sizeJson, null, 2));
|
36 | return "Overwrite file with sizes";
|
37 | });
|
38 |
|
39 | message("End build size conversion");
|
40 | } else {
|
41 | error(`${sizeSnapshotPath} not found`);
|
42 | }
|
43 | })();
|