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?
Here is another answer that uses the Purgecss programmatic API directly.
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 { writeFile, stat } from "fs/promises"
import { PurgeCSS } from "purgecss"
const purgeCSSResult = await new PurgeCSS().purge({
content: ["./dist/**/*.js", "./dist/**/*.html"],
css: ["./dist/**/*.css"],
})
await Promise.all([
...purgeCSSResult.map(async ({ css, file }) => {
const initialSize = (await stat(file)).size / 1024
await writeFile(file, css)
const postSize = (await stat(file)).size / 1024
console.log(`${file}: ${initialSize} -> ${postSize} KB`)
}),
])
npm run build && node ./scripts/purgecss.mjs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With