Removing unused CSS with Purgecss/UnCSS

Hi all,
I’ve been fighting with this for years, I used to use Uncss with a wget-spidered sitemap, later Purgecss with elaborate regexes… until I realized that I pretty much always want to

  • whitelist everything in resources/assets/styles/
  • purgify everything from node_modules (usually a CSS framework)

I haven’t found a clean option or plugin to do just this, but a workaround with purgecss start ignore. It needs more setup, which I detailed in this gist.

(I hope it’s OK to just link it here – this is my first post. HMU if I should unwrap it here & feel free to do so yourself!)

4 Likes

I had a similar setup to yours with purgecss start ignore comments but sometimes they weren’t reliable and styles got purged anyway.

I switched to whitelister and it works perfectly so far. Also, it keeps stylesheets cleaner and config is where it should be, that is in JS not CSS.

Here is an example how to whitelist contents of a folder:

whitelist: [
  "fade",
  "collapse",
  "collapsing",
  "in",
  "show",
  "modal-open",
  "modal-backdrop",
  "lazyloaded",
  "is-active",
  ...whitelister([
    "resources/assets/styles/common/*.scss",
    "resources/assets/styles/components/*.scss",
    "resources/assets/styles/layouts/*.scss",
    "resources/assets/styles/objects/*.scss",
  ]),
],

Thanks @mmirus for the tip!

4 Likes

Hi, does someone know how to use the rejected function of Purgecss with Sage? I’m trying to see which css is stripped out. I don’t get it working.

new Purgecss({
....
    rejected: true
})

https://www.purgecss.com/configuration#options

Great, thank’s folks. :star_struck:

after trying this i got

error An unexpected error occurred: "could not find a copy of webpack to link in /home/daadir/Sites/valet/mifal/web/app/themes/mifal/node_modules/purgecss-webpack-plugin/node_modules".

And since i had so much trouble spinning up sage, i decided to skip purgeCSS for the moment and went to yarn start which now gives me

/bin/sh: 1: webpack: not found
error Command failed with exit code 127.

It broke yarn?

Running yarn fixed it. …

This works beautifully, thanks a lot. :slight_smile:

1 Like