I’ve just released postcss-minify, a PostCSS plugin that reduces the size of CSS source files by removing comments and unnecessary whitespace. It’s very simple—just 50 lines of code—but I think that in many cases it offers all you need.
postcss-minify is a minimalist alternative to sophisticated CSS optimizers like cssnano, csso and clean-css. These projects analyze your CSS and find ways to rewrite it in order to reduce the total character count. For example, they can merge rules with the same selector, rewrite longhand properties using shorthand equivalents, and precompute
calc() expressions that evaluate to constants.
These clever techniques can help you squeeze a few more bytes out of your CSS, but they come with a lot of complexity. You may encounter bugs in these tools that make unsafe changes to your CSS, or find that changes which are theoretically safe behave surprisingly in older browsers. For some projects, the bytes saved may not be worth the risk incurred by this added complexity.
In contrast to these powerful optimizers, postcss-minify only makes trivial modifications to its input: it removes unnecessary whitespace and discards comments. This means it can be very simple (just 50 lines of code) and carry less risk of modifying your CSS in a way that breaks your website.
It turns out that in many situations, postcss-minify’s naive approach to minification performs almost exactly as well as much more sophisticated techniques. Here’s a quick experiment I ran where I minified bootstrap.css using various CSS optimizers and then compared the pre- and post-gzip size reductions.
|lines of code (SLOC)
|minified size of bootstrap.css 5.0 (195,075 bytes)
|ratio to unminified bootstrap.css
|after gzipping minified output
|ratio to gzipped bootstrap.css 5.0 (25,238 bytes)
As you can see, postcss-minify does almost as good a job of minifying this large, real-world CSS file as the more complex tools. And after gzip compression is applied to the results, the differences become insignificant. You’d save a mere 43 bytes by using clean-css over postcss-minify,2 which even on a 2G mobile connection represents an increased download time of only about 7ms.
Your mileage will vary of course. In certain situations (for example, when minifying CSS which was generated using Sass
@mixins), advanced techniques will be able to substantially reduce the size of your CSS code by merging rules and deleting duplicate declarations. But in many cases, naive minification will get you 90% of the compression with 2% of the complexity.