← All posts

Processing LESS "on the fly" with Nginx and Node.js

LESS, Nginx and Node.js logos

Today I started using twitter-bootstrap and decided to process less on the server rather than on the client side, just for fun. I immediately remembered the Habr article DIY server-side processing of LESS files “on the fly” and decided to implement what it described.

The idea is that all requests for “*.less” files will be proxied through Nginx and converted on the fly (you can also hook up nginx caching if needed) into css using node.js.

Installation

First, we need to install nginx and node.js:


sudo apt-get install nginx nodejs

Download the latest version of less.js from here and install it:


cd ~
wget -O adw0rd-less.js.tar.gz https://github.com/adw0rd/less.js/tarball/master
tar -xzf adw0rd-less.js.tar.gz
cd adw0rd-less.js-*

# Проверяем less
make test

Configuration

Add the host “example.loc” to “/etc/hosts”:


127.0.0.1 example.loc

Let’s configure Nginx

Add the upstream “lessserv” to “/etc/nginx/nginx.conf”:


upstream lessserv {
    server localhost:1337;
}

Edit your server config for “example.loc” — “/etc/nginx/sites-available/example.conf”:


server {
    listen 80;
    server_name example.loc;
    root /path/to/example;

    location ~* \.less$ {
        proxy_pass http://lessserv;
    }
}

After that, don’t forget to add it to sites-enabled and reload Nginx:


ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/example.conf
sudo nginx -s reload

Now let’s move on to node.js

In the file “bin/lessserv”, you can specify the listen_host and listen_port you need. The defaults are:


var listen_port = 1337,
    listen_host = "127.0.0.1";

Start lessserv, which will proxy our less files:


cd ~/adw0rd-less.js-*
node bin/lessserv --path=/path/to/example

Check this link: http://example.loc/bootstrap/less/bootstrap.less. If it serves a ready-to-use css file, you’ve got everything working!

Of course, the extracted bootstrap directory must be present in “/path/to/example”.

Then you can include it in your html like this:


<link rel="stylesheet" type="text/css" href="http://example.loc/bootstrap/less/bootstrap.less" />

P.S. Basically, this article is a “big Like” for the Habr article, though it goes into more detail on configuration, fixes the instructions (proxy_pass instead of proxy_path), and also slightly improves “less.js” on GitHub :)

Comments are closed. Read the original discussion in Russian →