Auto-compile LESS file to CSS in emacs

LESS CSS is a great way of writing CSS code, thanks to its set of extended features that are not at all possible with CSS. Nested rules, variables, color functions, etc make it very handy. As the final output seen by the browser is plain CSS, there is no need for any third-party library or whatever.

Being an emacs user (and a fan) for a while, I’ve been looking for a way to compile LESS files to CSS, as and when they are saved. It would be even better if I could bind it to a keyboard shortcut, say F9. (This is not something big, just that I didn’t do it so far.)

My directory structure is like this:
LESS files in /some/path/less/
CSS files in /some/path/css/

So compiling a LESS file, say /some/path/less/style.less should output to /some/path/css/style.css

Here is the code that you have to add to .emacs

;; Function to compile current buffer (if it's a LESS file) to CSS
(defun compile-less-css ()
  "Compile LESS to CSS"
  (if (string-match ".less$" (buffer-file-name))
    (async-shell-command (concat "lessc -x " (buffer-file-name) " "
      (file-name-directory (directory-file-name (file-name-directory buffer-file-name)))
      "css/" (file-name-sans-extension (file-name-nondirectory buffer-file-name)) ".css") nil nil))

;; HotKey  to compile LESS to CSS
(global-set-key '[f9] 'compile-less-css)

;; To compile whenever the file is saved, uncomment the following line:
;(add-hook 'after-save-hook 'compile-less-css)

After saving the file, load the file so that the changes take effect. To load the file,
Mx load-file.

Enter .emacs in the prompt. Done! Now open a LESS file in emacs and press F9.

Happy hacking 🙂

Leave a Reply