NodeJS asset pipeline with Handlebars

Coming from Rails we wanted a solid asset pipeline in our Node/Express projects. This article shows how to setup connect-assets with Bower and Handlebars as templates. We also setup Sass and CoffeeScript and add jQuery and Bootstrap to your project.

Development setup

Lets presume you’ve started your Express App using the Express application generator something like this:

express --hbs --css sass appname

First install all we need in your Node/Express project.

npm install connect-assets bower coffee-script --save-dev

Next configure your app to handle the connect-assets helpers css, js and assetPath. In your app.js put:

var connectAssets = require("connect-assets")({paths: ['assets/js', 'assets/css', 'bower_components']});
app.use(connectAssets);
var hbs = require('hbs');
hbs.registerHelper('css', function() {
  var css = connectAssets.options.helperContext.css.apply(this, arguments);
  return new hbs.SafeString(css);
});
hbs.registerHelper('js', function() {
  var js = connectAssets.options.helperContext.js.apply(this, arguments);
  return new hbs.SafeString(js);
});
hbs.registerHelper('assetPath', function() {
  var assetPath = connectAssets.options.helperContext.assetPath.apply(this, arguments);
  return new hbs.SafeString(assetPath);
});

Now create a /assets/js and assets/css dir to add your Javascript/CoffeeScript and CSS/Sass files.

/assets/css/application.scss:

//= require bootstrap-sass/assets/stylesheets/_bootstrap
body {
  padding: 50px;
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
  color: #00B7FF;
}

/assets/js/application.js.coffee:

# bower components:
#= require jquery/dist/jquery
#= require bootstrap-sass/assets/javascripts/bootstrap

And finally use the connect-assets helpers in your templates:

<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
    {{{css 'application.css'}}}
    {{{js 'application'}}}
  </head>
  <body>
    <p>An example assetPath: {{{assetPath 'application.css'}}}</p>
    {{{body}}}
  </body>
</html>

Production deploy

To compile your assets use the connect-assets cmd-line tool.

./node_modules/.bin/connect-assets -i bower_components -o public/assets

This will result in nicely minified and hashed assets ready for your CDN.