Wednesday, August 26, 2009

Visual Studio 2008 Post-Build Event and Minify Using YUI Compressor

A time tested way to shrink and optimize JavaScript and CSS is to minify and obfuscate your files. Yahoo (High Performance Web Sites Rule 10) and Google (Minimize Payload Size) have best practices recommending minifying JavaScript.

The YUI Compressor is an excellent open source tool for this; the best I have found. My real world use reduced the size of the regular CSS and JavaScript files by 45%. Gzipping the files reduced CSS files by an additional 25% and JavaScript files by an additional 36%. Resulting in 75%+ smaller files.

Here is a batch file snippet which should speed up implementing this into your build process:

SET YUICOMPRESSOR=%Minify%\yuicompressor-2.4.2.jar
IF "%JAVA_HOME%" == "" (
 ECHO Searching for Java...
 for /f %%j in ("java.exe") do (set JAVA_HOME=%%~dp$PATH:j)
)
ECHO Java: %JAVA_HOME%
ECHO YUICOMPRESSOR: %YUICOMPRESSOR%
IF EXIST "%YUICOMPRESSOR%" (
 IF NOT "%JAVA_HOME%" == "" (
  ECHO Deleting Minified files, TFS can make these readonly and the compressor will not overwrite read only files...
  del /F "%CD%\<Path To Script Directory>\core.min.js"
  del /F "%CD%\<Path To Styles Directory>\core.min.css"
  ECHO Done.

  "%JAVA_HOME%java" -jar "%YUICOMPRESSOR%" -v --type JS -o "%CD%\<Path To Script Directory>\core.min.js" "%CD%\<Path To Script Directory>\core.js"
  "%JAVA_HOME%java" -jar "%YUICOMPRESSOR%" -v --type CSS -o "%CD%\<Path To Styles Directory>\core.min.css" "%CD%\<Path To Styles Directory>\core.css"
 ) ELSE (
  ECHO ERROR: Java is not installed, no Minification
 )
) ELSE (
 ECHO ERROR: YUI Compressor not found.
)

Also note that if a build event echos a line starting with "ERROR", not sure if it is case sensitive, the Visual Studio and Team Foundation Server will set that step as a failure and alert as expected. Remove the "ERROR:" text from the echo lines to allow the build to proceed if it cannot find the compressor or java.

No comments: