Automatically compress and combine CSS and Javascript files

Using a simple bat file you can compress and combine several CSS and Javascript files in a single action.

First you’ll need to download the YUI Compressor. This tool uses java so you need to have it installed in your computer.

I separate the functionality in two bat files. minify.bat and deploy.bat.

Let’s look at the minify.bat:

set yui="<full path to file>\yuicompressor.jar"
set css="<full path to css folder>"
set js="<full path to javascript folder>"

cd %css%

type  print.css typography.css style.css > style.temp.css
java -jar %yui% style.temp.css > style.min.css
del style.temp.css

cd %js%

type script1.js script2.js script3.js > scripts.temp.js
java -jar %yui% scripts.temp.js > scripts.min.js
del scripts.temp.js

First I set the full path to the yuicompressor tool, to the folder where I have the CSS files that need compressing and to the JavaScript folder. Replace this with your paths.

Then I combine all the files into a single temp file. I compress the file using the yui tool and finally delete the temp.

Now let’s look at the deploy.bat. It’s useful to have the deployment and minification separated if you have multiple environment you need to deploy to (test, acceptance, production).

@call minify.bat
copy "<full path to file>\style.min.css" "<full path to destination folder>" 
copy "<full path to file>\scripts.min.js" "<full path to destination folder>" 

Here we just copy the the files to the destination folder.

Now just run the deploy.bat and watch your files being compressed and combined automatically.

Related articles