Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, Express and css, js, image assets

I would like to have all javascript, css and images that are sent to the browser to be concatenated, minified and have a md5 cache busting filename. I've been able to achieve this with packages like connect-assets and others.

However I have not been able to add the md5'ed image filename into the css before it is processed.

I am using Less css templates.

Any pointers to packages that could help me would be great.

eg

image.png is converted to image-455454545.png
css references background-image: url(image.png) -> should change to image-455454545.png

like image 352
robzolkos Avatar asked Aug 13 '12 12:08

robzolkos


1 Answers

As far as I know, Less doesn't have the ability to utilize user-defined functions. Stylus, however, does. So if you're willing to hop onto an alternate CSS preprocessor, then there is great fun to be had! (Stylus is really very simliar to Less, and it shouldn't take much to switch to it. Plus connect-assets already supports Stylus, so it should plug into your environment easily.)

server.js

var fs = require('fs');
var stylus = require('stylus');

stylus(fs.readFileSync("styles.styl", 'utf8')) //load stylus file
  .define("versionedFile", versionedFile) //add our custom function to the stylus env
  .render(function(err, css){ //render!
    if (err) {
      throw err;
    }

    fs.writeFileSync("styles.css", css); //write the compiled css to a .css file
});

//our custom function
function versionedFile(filename) {
  ... lookup versioned file of filename ...
  return "versionedFilename.png"
}

styles.styl

.image-block {
  background-image: url(versionedFile('unversionedFilename.png')); //this is how we use our custom function
}

Which will compile into:

styles.css

.image-block {
  background-image: url("versionedFilename.png"); //hooray!
}
like image 179
redhotvengeance Avatar answered Sep 23 '22 00:09

redhotvengeance