I'm using PurgeCSS CLI to delete unused css classes in my React project.
I'm using this command: purgecss --css src/**/*.css --content src/**/*.js
, what is doing is scanning all the js files in /src, detecting unused classes in css files and returning them to me in the console. PurgeCSS contains an --output flag to write files changed in an specific directory, is there any way to rewrite css files in each folder?
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.