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 |
|
24 | await log(async () => {
|
25 | sizeJson.module = convertSize(
|
26 | sizeJson[pkg.main].gzipped,
|
27 | units.values(),
|
28 | units[units.length - 1]
|
29 | );
|
30 | return "Convert module size";
|
31 | });
|
32 |
|
33 | await log(async () => {
|
34 | writeFileSync(sizeSnapshotPath, JSON.stringify(sizeJson, null, 2));
|
35 | return "Overwrite file with sizes";
|
36 | });
|
37 |
|
38 | message("End build size conversion");
|
39 | } else {
|
40 | error(`${sizeSnapshotPath} not found`);
|
41 | }
|
42 | })();
|