• Sage

Removing Unused CSS with Purgecss/UnCSS in Sage

Recently, I’ve been looking for a quicker alternative to UnCSS, since it is slow and often flaky. I thought PurifyCSS would be the answer since it has a nice webpack plugin, however, it doesn’t remove similar named selectors, which — if you use something like Tachyons — can be a lot. As of writing this, the main repo seems to be unmaintained as well.

Purgecss

Purgecss was originally thought of as the v2 of purifycss.1

Purgecss is a tool that works well and is actively maintained. It also has a handy webpack plugin. And though it has nothing in it, this repo looks promising as well.

Using Purgecss with Sage

Add the webpack plugin (and glob-all) to your Sage project:

yarn add --dev purgecss-webpack-plugin glob-all

Then drop the plugin in the webpack optimize config:

// resources/assets/build/webpack.config.optimize.js

// ...
const glob = require('glob-all');
const PurgecssPlugin = require('purgecss-webpack-plugin');

module.exports = {
  plugins: [
    // ... 
    new PurgecssPlugin({
      paths: glob.sync([
        'app/**/*.php',
        'resources/views/**/*.php',
        'resources/assets/scripts/**/*.js',
      ]),
      whitelist: [ // Only if you need it!
        'pr3','pv2','ph3',
        'mb1',
        'input',
        'tracked-mega'
      ],
    }),
  ],
};

Keep in mind that this will only process if you run yarn build:production as it is in the optimize config file. You could load this in the main config, however, removing CSS should be equated to minifying your CSS, which is reserved for the production build script.

As you may have noticed above, a small drawback is the need to whitelist any CSS that’s not in the specified paths, which makes using this on a site with a plugin like HTML Forms a bit painful.

Using UnCSS

Though UnCSS is more accurate since it loads the actual pages to figure out which classes are being used, this means every possible view must be shown and you’ll need to manual add the sitemap.

yarn add --dev uncss postcss-uncss

Then in the PostCSS config:

// resources/assets/build/postcss.config.js

// ...
const uncssConfig = {
  html: [
    'http://example.test',
    // Your entire sitemap added manually
    // or some other way if you’re clever (wget is handy for this).
  ]
};

// ...

module.exports = ({ file, options }) => {
  return {
    parser: options.enabled.optimize ? 'postcss-safe-parser' : undefined,
    plugins: {
      'postcss-uncss': options.enabled.optimize ? uncssConfig : false, // ← Add the plugin
      cssnano: options.enabled.optimize ? cssnanoConfig : false,
      autoprefixer: true,
    },
  };
};

Read the discussion on Roots Discourse

Ready to checkout?