22 May 2013

How to over-engineer a static HTML site with Grunt

I have many little projects that start off as a single HTML, CSS, and JS file. I often want to use Less CSS and maybe I want to use Coffeescript. Ideally this could just work, without any client-side compilation too.

In the pursuit of this ideal, I decided to try out GruntJS, which calls itself “the JavaScript task runner.” After quite a bit of trial and error + googling around the web, I was able to setup a project that auto-compiles .less and .coffee files and builds a production version of the project that combines, minifies, and versions static assets.

You can fork the project on github, which is elegantly named static-less-coffeescript-grunt-project.

You can have it watch and compile the less and coffee files under the src directory by running grunt watch or just build everything into the dist directory by running grunt.

The main task that glues things together is grunt-usemin, which let’s you define groupings of CSS and JS files in your HTML, e.g.,

    <!-- build:css css/app.css -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <!-- endbuild -->

Despite the markup looking really nice and neat in HTML, it was a bit confusing to setup, but I ended up figuring out (I think) that it’s supposed to setup a pipeline between useminPrepare and usemin to do all of the concatting and minification work.

I’m sure there could be improvements to how I’ve set it up, but it has been working pretty well for me, and I used it to build the initial version of the Daisy Office Yoga website.

Update - June 2014: I used this to build the launch website for Ringly. I updated dependencies and added a new one to version the static file URLs, which is ideal for caching of static assets with grunt-filerev. I opted to only version the CSS and JS, leaving it to the developer to have to come up with new filenames if images are updated, but it can easily be enabled for images too.




Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · rss