Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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";
//...
@kingkero

This comment has been minimized.

Copy link

commented Mar 21, 2019

Thanks for this gist!

Does it make sense to add purgecss-with-wordpress?

// resources/assets/build/webpack.config.optimize.js
const glob = require('glob-all');
const PurgecssPlugin = require('purgecss-webpack-plugin');
const purgecssWordPress = require('purgecss-with-wordpress')
//...
module.exports = {
  plugins: [
    //...
    new PurgecssPlugin({
      paths: glob.sync([
        'app/**/*.php',
        'resources/views/**/*.php',
        'resources/assets/scripts/**/*.js',
      ]),
      whitelist: purgecssWordPress.whitelist,
      whitelistPatterns: purgecssWordPress.whitelistPatterns,
    }),

This shouldn't have an impact, since custom scripts are ignored via the PurgeCSS comment, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.