Skip to content

Instantly share code, notes, and snippets.

@bikubi
Created March 1, 2019 12:39
Show Gist options
  • Save bikubi/2a27e7ab290db0501c3d681bb9b48312 to your computer and use it in GitHub Desktop.
Save bikubi/2a27e7ab290db0501c3d681bb9b48312 to your computer and use it in GitHub Desktop.
Simple Purgecss setup for Roots Sage WordPress starter theme

Why

  1. Sage doesn't come with Purgecss (or uncss, etc.)
  2. Say, we use Bulma -- suddenly dist/main.css grows by 400K!
  3. Let's purge it!
  4. Oh dang, we need to whitelist /\.wp-/, /\.post-type/, /myfancylightbox/...
  5. Wait we are whitelisting pretty much everything from /resource/assets/styles!
  6. Isn't there an option to purge /node_modules/**/* only?
  7. Nope.
  8. purgecss start ignore, strategically placed, to the rescue!

Now, this might not be 100% effective, but it is very convenient. YMMV!

Installation

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

Set up Webpack plugin

// 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',
      ]),
    }),

Configure Sage's PostCSS

// resources/assets/build/postcss.config.js
// we need to keep "important" comments
const cssnanoConfig = {
  preset: ['default', { discardComments: { removeAll: false } }]
//                                                    ^^^^^

Edit main.scss

// resources/assets/styles/main.scss

@import "common/variables";

/** Import everything from autoload */
@import "./autoload/**/*";

/**
 * Import npm dependencies
 *
 * Prefix your imports with `~` to grab from node_modules/
 * @see https://github.com/webpack-contrib/sass-loader#imports
 */

/*! purgecss start ignore */
// note the exclamation mark, which makes this comment "important"!
// everything above this line will be purged!
// everything below it will land in dist/main.css!

/** Import theme styles */
@import "common/global";
//...
@corycodes
Copy link

Hi!

I try to implement the PurgeCSS only but I am getting error on Sage 9

Cannot read property 'compilation' of undefined

You will have to install an older version of the PurgeCSS Webpack plugin if you're using Sage 9. This is because Sage 9 utilizes Webpack 3, and recent versions of the PurgeCSS for Webpack plugin utilize Webpack 4.

The latest version to work with Sage 9 is 0.23.0. Run the following and re-run your build to fix your issue:

yarn add --dev [email protected] glob all

@john-dave-manuel
Copy link

Thanks for the suggestion. I will try and let you know

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment