Skip to content

Instantly share code, notes, and snippets.

@mtrefzer
Last active November 12, 2021 09:57
Show Gist options
  • Save mtrefzer/c9921a7a5fd70266df4e09d259a6af74 to your computer and use it in GitHub Desktop.
Save mtrefzer/c9921a7a5fd70266df4e09d259a6af74 to your computer and use it in GitHub Desktop.
Angular: Use PurgeCSS in postbuild script

Howto

Angular: Use PurgeCSS in a postbuild script

Install ts-node and purgecss as devDependencies

$ npm i -D purgecss
$ npm i -D ts-node

Add postbuild to package.json

...
"postbuild": "ts-node path/to/purge-css.ts",
...

Add purge-css.ts and adjust the appDistPath in the script.

import * as util from 'util';
import * as child from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
const exec = util.promisify(child.exec);
interface FileData {
file: string;
originalSize: string;
newSize?: string;
}
function getFilesizeInKiloBytes(filename: string): string {
const fileSizeInBytes = fs.statSync(filename).size / 1024;
return fileSizeInBytes.toFixed(2);
}
function getFilesFromPath(dir: string, extension: string): Array<string> {
return fs.readdirSync(dir)
.filter(e => path.extname(e).toLowerCase() === extension);
}
function getOriginalFileSize(files: Array<string>): Array<FileData> {
return files.map((file) => ({
file,
originalSize: getFilesizeInKiloBytes(`./${appDistPath}/${file}`) + "kb",
}));
}
function getPurgedFileSize(data: Array<FileData>): Array<FileData> {
return data.map((item) => ({
...item,
newSize: getFilesizeInKiloBytes(`./${appDistPath}/${item.file}`) + "kb",
}));
}
function runPurgeCss(): child.PromiseWithChild<{ stdout: string; stderr: string; }> {
return exec(`purgecss -css ${appDistPath}/*.css --content ${appDistPath}/index.html ${appDistPath}/*.js --output ${appDistPath}/`);
}
const appDistPath = 'path/to/app/dist';
const cssFiles = getFilesFromPath(`./${appDistPath}`, '.css');
if (!cssFiles || cssFiles.length <= 0) {
console.log("no css files to purge");
} else {
(async () => {
let data: Array<FileData> = getOriginalFileSize(cssFiles);
console.log(`purgecss -css ${appDistPath}/*.css --content ${appDistPath}/index.html ${appDistPath}/*.js`);
console.log("---- PurgeCSS ----");
await runPurgeCss();
data = getPurgedFileSize(data);
console.table(data);
})()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment