• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

146
Views
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?

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error