A Rake Task to Concatenate and Compress Javascript Files
Posted: March 2nd, 2008 Tags: Javascript, Ruby on Rails, Web development, wshlst.comA while ago, I wrote about a Ruby script to concatenate and compress Javascript files for my wshlst application. I’ve changed things around a bit since that article, so I thought it was time for an update.
Background
wshlst uses a lot of Javascript. When developing, I want to have all of my JS files listed in my index.html page. But in production mode, I want a single JS file. So I wrote a script to read in my index.html file, find all the references to my Javascript files, and write out a new HTML file that contains a reference to a single JS file that was created by concatenating and compressing all the JS files.
As an example, have a look at what my index.html page looks like in development mode and in production mode.
Ruby Script → Rake
When a server move prompted me to upgrade to Subversion and Capistrano, I decided to turn my Ruby script into a Rake task that I could trigger from my Capistrano deploy: minify.rake
Capistrano
I added a line to my Capistrano deploy.rb file to run rake minify on the server after updating from Subversion:
run "cd #{release_path} && rake minify RAILS_ENV=#{rails_env}"
Apache
I also added a few lines to my httpd.conf file to support this. First, since the Rake task combines all the JS files into a single JS file but Capistrano deploys the entire app, I wanted to restrict access to everything in the javascripts directory:
# Don't allow access to the javascripts directory (all JS should be in minified js file) RewriteRule ^/javascripts/ - [F]
Then, because the Rake task reads index.html and outputs a file called index-mini.html, I wanted to send all requests for / and /index.html to /index-mini.html:
# Rewrite index.html to index-mini.html RewriteRule ^/index.html$ /index-mini.html [QSA] # Rewrite index to check for static RewriteRule ^/$ /index-mini.html [QSA]
Why Not Use AssetPackager?
For a normal Rails application, AssetPackager is probably the right solution to this problem. However, wshlst doesn’t use Rails to generate the UI (it’s all done in Javascript), so AssetPackager wouldn’t work.