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); | |
})() | |
} |