CSS Compression

I came to the shocking realization today that my production build process for front-end stuff absolutely sucks so I set forth to fix that little problem.

There are a few things that I do before I release any code into production, first is to run the unit tests, second is to compress the CSS, finally I compress the Javascript run a few more unit tests and release. Anyone listening would say, "Sounds like a complex process but I bet it's all automated." Well that would be wrong! For the longest time I have been doing this all manually for whatever reason. Tonight I sat down and banged out a bunch of Python scripts to automate it.

Anyhow, on to the topic of the post, a CSS compressor. Well, I looked around for a while for a suitable CSS compressor that could be run from a Linux command line so it could be integrated into the production build process easily. I came up with nothing really viable so I sat down and wrote one.

The compressor is Python based and fairly simple. You are welcome to use it but keep in mind that it is fairly aggressive. If you run this puppy on your dev code without a backup your going to have a hell of a time straightening things out. Also keep in mind this is the second Python program I have ever written so the style may suck, pointers are appreciated. From my tests on a few CSS files that I have laying around it will strip all extraneous stuff out of your file whilst not breaking the standards compliance of your file. If you run into a case where it DOES break something, let me know and I will fix it. I wrote this about midnight with no coffee in sight so I may well have missed some subtlety.

Usage is simple.... cmpcss your_dev.css > your_prod.css. It's also dead simple to integrate into a larger build process.

My tests show that it compresses the file anywhere from 20-35% but YMMV.

Anyhow... enjoy.

Update (6/21/06): My regular expression for matching comments was WAY too simple, I re-wrote it today after it blew up on one of my files at work. Make sure you get the latest version.