25 May 2010

A Quick and Dirty Production JavaScript File Builder with Windows Batch Programming

A while back, I needed a simple script to minimize and unite a few javascript source files into one big file to decrease loading times (and just to make things neater). The difficulty level came from the fact that I needed to do this on a Windows server, and most tutorials and whatnot I could find explained it for UNIX/Linux servers.

So, after some research, I decided to use excellent YUI Compressor (found here), and utilizing a few Windows Batch commands I picked up here and there, I created a .BAT file:

echo off
set buildFile=../www/js-lib/app-deploy/final-build-file.js
set libDir=../html/js-lib
set yuiComp=./yuicompressor-2.4.2/build/yuicompressor-2.3.5.jar

FOR %%G IN (file1.js file2.js directory/file3.js) DO (
echo on
Echo Compressing %%G...
echo off

java -jar %yuiComp% --preserve-semi --line-break 100 %libDir%/%%G >> %buildFile%
)

Simply change the directories and file names to what you need (I trust you can figure this out), stick all that into a .BAT file, and then run it from your Windows command line -- it'll create a nice combined javascript source file at the location of "%buildFile%".

Issues: You'll need to delete the older build file whenever you run the batch command each time -- I couldn't find a way to delete a file on the server I was working with (using Windows batch commands), and if you run this batch file without deleting the older build file it creates first, it'll simply append your new build file onto the end of the old one!

Links:
BATCH FILE COMMANDS: Simple programming commands in a batch environment
Introduction to the Windows Command Prompt
MS DOS Copy Command Help

Fixed Code Blocks

The wonderful JavaScript library I've been using courtesy of AlexGorbatchev.com to display inline code here on my blog, responsible for blocks of code like this:

function () {
    alert("Hello world!");
}

Hasn't been working on my blog for the past few weeks (or longer, maybe), but it's fixed now. All code examples now show up correctly.

Interested in using it for your own blog? Go here: http://alexgorbatchev.com (There's even a hosted version for users of Blogger.com.)