Archive for the ‘shell’ Category

Articles

Combining and minifying files (in order) using Shell Scripts

In shell,Uncategorized on October 10, 2013 by Matt Grande Tagged: , , , , ,

I’ve been working on an application using Backbone.js recently. I really enjoy it, however I realised today that I now have over 100 javascript files in my project. This means that every time my page loads, the browser is making 100 separate HTTP requests. Very quickly, your site slows down.

The obvious solution is to combine all my scripts into one file and minify. I’ve done this several times before, but I needed to make sure that certain files loaded in a certain order, so I whipped up a shell script to ensure some of the files are pushed to the front of the line.

Having never really done that much shell scripting before, this wasn’t the easiest task for me. To help save others some time, I’ve attached my script and documented it pretty well. Let me know if you have any questions!

screenshot

Above, you’ll see our (sample) folder structure. Under the models subfolder, we have tab.js, which needs to be loaded before subtab.js.

Below, you’ll see the gist of what I’m doing. If you have any sort of shell experience, I’m sure this isn’t a revelation, but I wish I had something like this when I started writing earlier today!

A few things to note:

  1. I highly recommend adding this code as a git hook, if you want your combined JS to be in source control
  2. The heavy lifting is done with the fabulous YUI Compressor, which requires Java to be installed (It also does CSS minification).
  3. Remember to chmod your compression script to allow you to execute or else it won’t work!
Advertisements