Skip to content

Instantly share code, notes, and snippets.

@kievsash
Created September 4, 2024 07:34
Show Gist options
  • Save kievsash/bc611795d0be865316213529ad5d9457 to your computer and use it in GitHub Desktop.
Save kievsash/bc611795d0be865316213529ad5d9457 to your computer and use it in GitHub Desktop.
purgeCss
// "postbuild": "node environments/postbuild.js",
// from https://dev.to/dylanvdmerwe/reduce-angular-style-size-using-purgecss-to-remove-unused-styles-3b2k
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
// find the styles css file
const files = getFilesFromPath('./dist', '.css');
let data = [];
if (!files && files.length <= 0) {
console.log("cannot find style files to purge");
return;
}
for (let f of files) {
// get original file size
const originalSize = getFilesizeInKiloBytes('./dist/' + f) + "kb";
var o = { "file": f, "originalSize": originalSize, "newSize": "" };
data.push(o);
}
console.log("Run PurgeCSS...");
exec("purgecss -css dist/*.css --content dist/index.html dist/*.js -o dist/", function (error, stdout, stderr) {
console.log("PurgeCSS done");
console.log();
for (let d of data) {
// get new file size
const newSize = getFilesizeInKiloBytes('./dist/' + d.file) + "kb";
d.newSize = newSize;
}
console.table(data);
});
function getFilesizeInKiloBytes(filename) {
var stats = fs.statSync(filename);
var fileSizeInBytes = stats.size / 1024;
return fileSizeInBytes.toFixed(2);
}
function getFilesFromPath(dir, extension) {
let files = fs.readdirSync(dir);
return files.filter(e => path.extname(e).toLowerCase() === extension);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment