Sunday, May 13, 2012

Add support for LESS to Node.js connect-assetmanager package

The connect-assetmanager Node.js package allows you to combine multiple javascript and CSS files into one and also do other manipulations like minification.

It's part of Mathias Pettersson's (mape) excellent node-express-boilerplate template.

If you're also using LESS for CSS here is some code you can add to get connect-assetmanager to process you're LESS files:

var assetsSettings;
assetsSettings = {
  js: {
    route: /\/static\/js\/[a-z0-9]+\/.*\.js/,
    path: "./public/javascripts/",
    dataType: "javascript",
    files: ["libs/underscore-min.js" "libs/jquery.mobile-1.1.0.min.js", siteConf.uri + "/nowjs/now.js", "site.js"],
    debug: siteConf.debug,
    stale: !siteConf.debug
  },
  css: {
    route: /\/static\/css\/[a-z0-9]+\/.*\.css/,
    path: "./public/stylesheets/",
    dataType: "css",
    files: ["libs/jquery.mobile-1.1.0.min.css", "style.less"],
    debug: siteConf.debug,
    stale: !siteConf.debug,
    preManipulate: {
      "^": [
        function(file, path, index, isLast, callback) {
          var match;
          match = path.match(/\.less$/);
          if ((match != null) && match.length > 0) {
            return less.render(file, function(e, css) {
              return callback(css);
            });
          } else {
            return callback(file);
          }
        }
      ]
    }
  }
};

The import part is the preManipulate line under css but I include my entire assetsSettings from a project to make it easier to understand.