Skip to content

Using PurgeCSS with Ember.js

After watching talks about Functional CSS at Ember Map, I started looking into starting to usetailwind for my future projects. The way tailwind works is that it generates a lot of CSS classes that you then use purgecss to remove. So I decided to try it on some of my existing Ember.js projects.

I ran it on Open Education Week and Val 202 web site. Both are built on top of Zurb Foundation. Here are results:

Open Education Week:
Before: 84.3 KB (14.91 KB gzipped)
After: 31.05 KB (7.04 KB gzipped)
A 52% reduction in gzipped size!

Val 202:
Before: 156.48 KB (24.5 KB gzipped)
After: 107.68 KB (18.45 KB gzipped)
A 24% reduction in gzipped size!

Not a bad improvement, since we get it almost for free, just by including it in the build pipeline. The only downsize is probably a few seconds longer production build time.

Using it in your Ember.js project

First install dependencies:

ember install ember-cli-postcss
yarn add --dev @fullhuman/postcss-purgecss

Then add it to your ember-cli-build.js

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const purgecss = require('@fullhuman/postcss-purgecss');

module.exports = function (defaults) {
  const app = new EmberApp(defaults, {
    postcssOptions: {
      filter: {
        enabled: true,
        plugins: [
          {
            module: purgecss,
            options: {
              content: ['./app/**/*.hbs', './app/**/.js'],
            }
          }
        ]
      }
    }
  });
  return app.toTree();
};

Finally, open your styles/app.scss or styles/app.css and modify it so purgecss doesn’t remove any of your custom CSS. 

// import framework like Foundation or Bootstrap here

/*! purgecss start ignore */

// your css and ember-addon @imports go here

/*! purgecss end ignore */

That’s all. If this isn’t enough, you can also set additional whitelistPatterns and whitelistPatternsChildren to keep additional CSS rules in your final build.

Thanks goes to @samselikoff for pointing me in the right direction to make this work.