Minifying and Combining my CSS Files Using Postcss and a Shell Script

Posted:

In my quest to improve my front-end skills, I have moved on to trying to optimize my CSS reduce the number of requests and total page size. I don't really want to use webpack, grunt, or anything similar. So, I decided to use postcss with a couple of plugins and a quick and dirty shell script to get the job.

First, I installed postcss (postcss@8.4.38) and cssnano (cssnano@7.0.1).

npm install cssnano postcss --save-dev

Next, I created a simple postcss.config.js file.

module.exports = {  
    plugins: [  
        require('cssnano')({  
            preset: 'default',  
        }),  
    ],  
};

cssnano will minify a single css file, like this:

 npx postcss raw_css/styles.css > css/styles.min.css

But, I have a few css files, and ideally I would like them combined into one minified file. To make this happen, I created a simple shell script.

#!/bin/bash  
  
cat raw_css/normalize.css raw_css/font-awesome.min.css raw_css/fonts.css raw_css/prism-okaidia.css raw_css/styles.css | postcss > css/bundle.min.css

With that working, my next thought was to purge out any unused css from the various libraries that I am using. For that, I installed purgecss (@fullhuman/postcss-purgecss@6.0.0) and a postcss plugin for purgecss.

npm i -D @fullhuman/postcss-purgecss 

And, to get that working, I modified my postcss.config.js file

const purgecss = require('@fullhuman/postcss-purgecss');  
  
module.exports = {  
    plugins: [  
        purgecss({  
            css: ['./raw_css/*.css'],  
            content: ['/Users/amy/Code/amykhar.dev/**/*.html']  
        }),  
        require('cssnano')({  
            preset: 'default',  
        }),  
    ],  
};

So, purgecss will look at my html files and my css files, and remove anything it doesn't think I'm using in the css files. For this simple site, it worked with no problems.

Before these steps, rendering the homepage took 12 http requests with a combined size of about 296kb of data. After, it's 7 requests with a combined size of about 120kb.

Later, I may add other postcss plugins to lint my css or otherwise improve things. But for now, this will do.