In web products, we see more and more JavaScript being used. This is a direct consequence of rapid AJAX adoption and improved client-side user experiences. As an interpreted language, there is no compilation phase to optimize the actual code before deployment. All JavaScript code is transmitted in raw form (comments and all) from the server to the client. Since each JavaScript file must be transmitted along with the page request, it makes sense to optimize these files as much as possible. As an added bonus, it's nice to strip out comments since you may not necessarily want your customer to see them (and yes, your customers will look at them!).
JSMin is a command line tool that will optimize your JavaScript files by removing comments, and redundant white-space. The resulting file is generally much smaller and more suitable for transmission over the web. I'll spare you the details about how this application works, but I will show you how you can integrate this tool into your build process.
Part of the power of having a build process is that you can inject optimization steps before or after your build. Using Nant, we can create a new optimization target that will be called just before our build and the optimized JavaScript files will be included in the resulting build.
1: <target name="minifyJs">
2: <foreach item="Line" in="JavaScripts.txt" property="jsFilename">
3: <echo message="Minifying JavaScript file: ${jsFilename}" />
4: <exec basedir="."
5: program="jsmin.exe"
6: commandline="${jsFilename} tempJS_min.js"
7: workingdir="."
8: failonerror="true" />
9: <move file="tempJS_min.js" tofile="${jsFilename}" overwrite="true" />
10: </foreach>
11: </target>
A few items in the build script above are worth mentioning. The JavaScripts.txt file contains paths to each JavaScript file that you would like to have optimized during the build. This allows you to control which JavaScript files get optimized. If you are comfortable with optimizing all of your JavaScript files, you can simply create a file list to optimize all files with a *.js extension. I would also like to mention that I used the C# port of JSMin instead since the command line arguments seemed to work a little better.
Optimizing your JavaScript files in your build process allows you to write legible JavaScript along with comments without having to worry so much about the performance penalties that you may incur from doing so. Enjoy!