April 26, 2013

JS and CSS bundling in Node.js

So, I needed a way to bundle and minify my javascript and css on this site. Node.js is awesome, because it has a bunch of libraries for that. But, not all of them work well with your deployment environment. This article is to cover 2 libraries, connect-assetmanager and bundle-up.

My quest first started with connect-assetmanager. It worked great….on my box. I was able to merge everything into a single file and leave it in the folder I wanted, for both css and javascript. Then I deployed to production.

The problem was connect-assetmanager uses the fs library’s file watcher. While it is awesome under linux boxes, they don’t work well in windows environments, and more specifically Windows Azure. This made me sad, because I want to have a library like what is built into ASP.net MVC.

Enter bundle-up. I have used this library, and it has been super easy to implement. Here, let me throw some code up here to show you guys why. Here is my server.js file:

 var BundleUp = require('bundle-up'); var express = require('express'); var app = express(); BundleUp(app, \_\_dirname + '\\assets.js', { staticRoot: \_\_dirname + '\\public\\', staticUrlRoot:'/', bundle:true, minifyCss: true, minifyJs: true }); 

Here, we are using express to host the site. So, we take express and get the app object to pass into Bundle-up. There we tell it, where the assets.js file is (more later), the public folder of your site, the root of your site, and some bools to tell whether to bundle and minify. Now, getting back to the assets.js file, let’s see what we are doing with that:

 module.exports = function(assets) { assets.root = _\_dirname; assets.addJs('/public/js/jquery.min.js'); assets.addJs('/public/js/bootstrap.js'); assets.addJs('/public/js/ejs\_production.js'); assets.addJs('/public/js/prettify.js'); assets.addJs('/public/js/site.js'); assets.addCss('/public/css/bootstrap-responsive.css'); assets.addCss('/public/css/prettify.css'); assets.addCss('/public/css/site.css'); } 

This file describes all of the files that you are using for javascript and CSS, as well as the root folder. Once we describe all of this, how do we add it to our page? Here is a layout page sample using ejs:

   ... <%- renderJs() %>   

renderStyles() and renderJs(), that’s it!!! Now, BAM! All the files get combined together into one, minified and makes development easy. The only problem I noticed so far is that the files get autogenerated each time the website is recycled. So watch out for that gotcha, but does what I expect :-).