Javascript minification in capistrano/webistrano

Photo: http://www.sxc.hu/photo/347930

Recently i had to automate the minification of specific javascripts. Since we don’t have a real build tool, i thought it was best to do this during deployment.
For (automatic) deployments our tool of choice is Webistrano, which is based on Capistrano, which is written in Ruby.

Capistrano has this concept of recipes, which are small scripts that you write to do specific tasks during deployment.
So, one of these tasks could be the minification of some javascript.

But for the minification and deployment of that, i was bound to some constraints:

  • We’re using the yuicompressor (java)
  • Deploy target machines do not have java installed
  • So we have to do the minification locally

After doing some initial research it was quite easy to do, and i came up with the following code:

The approach can be considered somewhat unusual, as the project’s files are first uploaded to the server. And after that the javascript is minified and uploaded seperately. This is mainly because I couldn’t find another hook within capistrano that fits my need.
Of course, you can rewrite this script to work with any other local command too.

Note/disclaimer: This script uses the copy_cache directive. I’m not a capistrano expert, but this variable might not be available to all deployment strategies. This script might not work for you if copied 1:1. But i suppose you get the idea.

  • Jeroen van Dijk

    What do you do when the minification fails? There is no guarantee that a uncompressed version will work as a compressed version.

    • The “run_locally” command checks the exit status of the command it runs. If the command fails, the deploy will fail and be cancelled/reverted.

      As an added fallback (for environments that do not run this recipe) there is an apache RewriteRule that rewrites to the original javascript file if the minified version does not exist.