Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite css files modified in PurgeCSS CLI

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?

like image 809
NuzzeSicK Avatar asked Aug 23 '26 12:08

NuzzeSicK


1 Answers

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
like image 120
Amin Avatar answered Aug 25 '26 04:08

Amin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!