8

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

1 Answer 1

7
+50

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!
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. How would the " ... lookup versioned file of filename ..." bit work? Sorry, I'm new to node so not sure if there's an easy way or not.
That really depends on how you're going about fingerprinting/versioning your files. If, for instance, the fingerprinting method you're using creates a manifest file (similar to Sprockets in Ruby), then you can look up the versioned filename there. I believe connect-assets stores its "manifest" in memory, via connect-file-cache.
It looks like there is a project that does just this for you github.com/lucasmazza/fingerprint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.