Wednesday, September 19, 2012

PHP, LESS CSS and css/js minify

UPDATE: Link and source updated on 19-apr-2013. See bottom of page


LESS CSS is a pre-processor for CSS that provides lots of added functionality to plain ol' CSS. For more info visit the LESS website.
Here is a brief description of what it does:
LESS extends CSS with dynamic behavior such as variablesmixinsoperations and functions. LESS runs on both the client-side (Chrome, Safari, Firefox) and server-side, with Node.js and Rhino
There is also a LESS plugin for Netbeans.


CSS and JS minify is the process of compacting CSS and JS files, in order to speed up page loads.

While there are lots of different ways of minifying CSS and JS files, I needed one that was simple to use and that was available on my dev PC.

I have combined a number of tools and have come up with the following solution that:
  • compiles LESS files into CSS, if the LESS files are newer than the corresponding CSS.
  • minifies the CSS files into .min.css if the CSS files are newer than the .min.css files.
  • minifies the JS files into .min.js if the JS files are newer than the .min.js files
The above is achieved by simply visiting a page on the local development PC. Every time the page is visited it executes all of the above.

For PHP projects, the dir structure could be as follows:
- <project root>
- - styles
- - scripts
- - LESS
- - etc

A LESS.INI file specifies which directories to process for JS and whcich for LESS and CSS.

The LESS directory contains the compile.phplessc.inc.phpcssmin-v3.0.1.php, Minifier.php and LESS.ini files. See download links inside the compile.php  sourcef file.

Compile.php is the one that does all the work.

While developing an app, I have a browser window open that points to
<project root>/LESS/compile.php.
Whenever I refresh it, all of the above actions are executed.
Magic!


Here is a link to the complete source of the version that I use.

Updates

Link and source updated on 19apr2013:
It also checks inside LESS files for @import statements and uses that to determine if the main LESS file needs to be recompiled.
- The LESS compiler emits more info in error messages


ps: Comments and/or links to this article are most welcome!