You can use the programmatic API to do so.
This code sets the purgecss's content to all the built HTML and JS files. Then processes each file and overwrites the file.
./scripts/purgecss.mjs
import { readFile, writeFile, stat } from "fs/promises"
import glob from "fast-glob"
import purgecss from "@fullhuman/postcss-purgecss"
import postcss from "postcss"
const sourceFiles = await glob(["./dist/**/*.html", "./dist/**/*.js"], {
dot: true,
cwd: process.cwd(),
onlyFiles: true,
absolute: true,
})
const cssFiles = await glob(["./dist/**/*.css"], {
dot: true,
cwd: process.cwd(),
onlyFiles: true,
absolute: true,
})
const postcssProcessor = postcss([
purgecss({
content: sourceFiles,
}),
])
await Promise.all([
...cssFiles.map(async (cssFile) => {
const cssString = await readFile(cssFile, "utf8")
const { css, map } = await postcssProcessor.process(cssString, { from: cssFile, to: cssFile, map: true })
await writeFile(cssFile, css)
if (map !== undefined) {
await writeFile(cssFile.replace(/\.css$/, ".css.map"), map.toString())
}
console.log(`${cssFile}: ${(await stat(cssFile)).size / 1024} KB`)
}),
])
npm run build && node ./scripts/purgecss.mjs
You will need to have fast-glob and postcss installed.