PurgeCSS is a tool designed to eliminate unused CSS from your project by analyzing your content and CSS files. It identifies the selectors used in your files and matches them with the ones in your content files, ultimately removing unused selectors from your CSS. This results in smaller CSS files. It is typically added in the post-build process.
Installing PurgeCSS:
npm install purgecss --save-dev
The following dependency is also required to execute PurgeCSS in custom script format."
npm install child_process path fs
Creating purgecss.js :
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
/* the path here should be the one where css
file is created by build process */
const files = getFilesFromPath('./dist/browser', '.css');
let data = [];
if (!files && files.length <= 0) {
console.log('unable to find style files to purge');
return;
}
for (let f of files) {
// get the original size of file
const originalSize = getFilesizeInKB('./dist/browser/' + f) + 'kb';
var o = { file: f, originalSize: originalSize, newSize: '' };
data.push(o);
}
console.log('Running PurgeCSS...');
exec(
'./node_modules/purgecss/bin/purgecss.js -css dist/browser/*.css --content'+
'dist/browser/index.html dist/browser/*.js -o dist/browser/',
function (error, stdout, stderr) {
console.log('PurgeCSS done');
for (let d of data) {
// get the size of new file
const newSize = getFilesizeInKB('./dist/browser/' + d.file) + 'kb';
d.newSize = newSize;
}
console.table(data);
}
);
function getFilesizeInKB(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);
}
Adding PurgeCSS to run post-build:
Use the following script in the package scripts and include the purgecss command with the build command.
"purgecss": "node ./purgecss.js",
"build": "ng build --configuration production && npm run purgecss"
Now, execute the build command to allow PurgeCSS to remove unused CSS and generate a new smaller CSS file.
npm run build
Result: PurgeCSS reduced the size of the CSS file by removing unused CSS.