harriyott.com

Yahoo YUI compressor and .Less with Visual Studio

CSS is great and everything, but it isn't that programmery. Less, and the .NET port, .Less add some useful things, like variables, operations, functions and mixins.

The basic workflow in Visual Studio is to edit the .less file, run it through the parser in the post-compile step, and include the generated CSS output in your HTML head as normal. More on this later.

There's a bit of an art deciding when to use these features and when to use CSS properly, so I've been using them cautiously at first. Variables are great for colours, as you can give them readable names; I for one can't tell what colour #BAD455 is without seeing the output. Ah, it's a sludgy colour. I can call my variable 'sludge' and use it throughout my stylesheet.

Mixins are super handy for the HTML5 / CSS3 items with multiple browser prefixes:

This can then be used anywhere you want a box shadow:

Minification

Javascript and CSS minification is all the rage, and is quite simple to do in .NET, thanks to the YUI compressor for .NET. It can be found with NuGet, as YUICompressor.NET. The setup details are on codeplex.

The idea is that the .js and .css files are compressed as a post-build step, with the files to be compressed listed in YuiCompression.targets, which is an MSBuild script included in your main .csproj file, thus:

And in YuiCompression.targets:

Any files listed in the item group will be squished together and minified into a single .js and a .css file, which can then be included in your HTML.

It can be a nuisance trying to debug compressed Javascript / CSS in development, so in my master page, I conditionally include the originals for debugging, and the compressed file for release versions:

Also a nuisance is editing .Less files. With plain CSS, I would edit the file, save it, and press F5 in the browser. With .Less, the CSS file must be regenerated. Rebuilding the whole Visual Studio solution is so much slower, but fortunately unecessary. Phil Haack's T4 script rebuilds just the .Less file. The cunning bit is how, when run, the file marks itself as unsaved. T4 scripts are run when saved, so every time the file is saved, .Less generates the CSS files again.

Using that feature, you can open T4CSS.tt in Visual Studio along with the .less file you're editing, and leave it open. Now, when saving the .less file, instead of pressing Ctrl-S, press Ctrl-Shft-S, which is saves all open files. This will save the T4 script (thus regenerating the CSS), and the changes will appear when you refresh the browser. Once setup, the only change to the edit / save / view cycle is pressing Shift when saving.

5 July 2011