Created
March 13, 2020 08:33
-
-
Save theKashey/01a9ddd3a77a4a79d8a26846609e6653 to your computer and use it in GitHub Desktop.
Report total entry size using webpack-imported
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const gzipSize = require("gzip-size"); | |
const stats = require("../build/imported"); | |
function collectSize(assets) { | |
return assets.reduce((acc, asset) => acc + (stats.assets.find(({ name }) => name === asset) || { size: 0 }).size, 0); | |
} | |
function collectGSize(assets) { | |
return assets.reduce((acc, asset) => { | |
const data = fs.readFileSync(`./build/${asset}`); | |
return acc + gzipSize.sync(data); | |
}, 0); | |
} | |
function formatTailLength(name, limit) { | |
return name + String(" ").repeat(limit - String(name).length); | |
} | |
function formatHeadLength(name, limit) { | |
return String(" ").repeat(limit - String(name).length) + name; | |
} | |
function dot3(val) { | |
const string = String(val); | |
return formatHeadLength(string, string.length + (string.length % 3 ? 3 - (string.length % 3) : 0)) | |
.split("") | |
.reduce((acc, c, index) => acc + (index > 0 && index % 3 === 0 ? "." : "") + c); | |
} | |
const report = { | |
total: {}, | |
chunks: {}, | |
}; | |
Object.keys(stats.chunks).forEach(chunk => { | |
const data = stats.chunks[chunk]; | |
const { load } = data; | |
const size = { | |
js: 0, | |
css: 0, | |
}; | |
const gsize = { | |
js: 0, | |
css: 0, | |
}; | |
load.forEach(chunkId => { | |
const { css = [], js = [] } = stats.chunkMap[chunkId]; | |
size.js += collectSize(js); | |
size.css += collectSize(css); | |
gsize.js += collectGSize(js); | |
gsize.css += collectGSize(css); | |
}); | |
console.log( | |
"-", | |
formatTailLength(chunk, 32), | |
"\t", | |
"js", | |
formatHeadLength(dot3(size.js), 12), | |
"/", | |
formatHeadLength(dot3(gsize.js), 12), | |
"\t", | |
"css", | |
formatHeadLength(dot3(size.css), 12), | |
"/", | |
formatHeadLength(dot3(gsize.css), 12) | |
); | |
report.chunks[chunk] = { raw: size, gzip: gsize }; | |
}); | |
const totalJS = stats.assets.filter(({ type }) => type === "js").reduce((acc, { size }) => acc + size, 0); | |
const totalCSS = stats.assets.filter(({ type }) => type === "css").reduce((acc, { size }) => acc + size, 0); | |
report.total = { raw: { js: totalJS, css: totalCSS } }; | |
console.log("\n"); | |
console.log( | |
"-", | |
formatTailLength("total", 32), | |
"\t", | |
"js", | |
formatHeadLength(dot3(totalJS), 12), | |
"\t", | |
"css", | |
formatHeadLength(dot3(totalCSS), 12) | |
); | |
fs.writeFileSync("./.bundle-size.json", JSON.stringify(report, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment