Node.js, Express and css, js, asset images

I would like to have all the javascript, css and images that are sent to the browser to be concatenated, minimized, and have the mb5 file name for busting. I was able to achieve this with packages like connect-assets and others.

However, I was not able to add the md5'ed file name to the css file before processing it.

I use less CSS templates.

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

eg

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

+8
express
source share
1 answer

As far as I know, Less is not able to use custom functions. However, the stylus does. So if you want to switch to an alternative CSS preprocessor, then you will have a lot of fun! (Stylus is really very similar to Less, and you should not switch to it much. Plus, connect-assets already supports Stylus, so it should easily connect to your environment.)

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 } 

What will be compiled into:

styles.css

 .image-block { background-image: url("versionedFilename.png"); //hooray! } 
+7
source share

All Articles