LESS.js Middleware for Connect/Express

3.1.0 · maintenance · verified Wed Apr 22

less-middleware is an HTTP middleware specifically designed to process LESS CSS files for web servers built with Connect.js or Express.js. It compiles .less files into .css on-the-fly when requested, or upon server restart with caching, and serves the resulting CSS. The current stable version, 3.1.0, is compatible with Less.js 3.9. While not on a strict schedule, releases typically follow major Less.js updates to maintain compatibility and leverage new features. Its key differentiators include robust caching mechanisms (including `cacheFile` for cross-restart caching), extensive preprocessing and postprocessing hooks (`preprocess.less`, `postprocess.css`), and fine-grained control over rendering options, making it suitable for both development and production environments by reducing disk I/O.

Common errors

Warnings

Install

Imports

Quickstart

This Express.js quickstart demonstrates how to integrate `less-middleware` to compile LESS files on the fly. It sets up the middleware to serve static files, enabling LESS compilation in a 'public' directory with different caching strategies for development and production environments, and basic Less rendering options like compression.

import express from 'express';
import lessMiddleware from 'less-middleware';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();
const publicPath = join(__dirname, 'public');

// Imagine a 'public' directory containing 'styles.less'
// app.use(lessMiddleware('/less', { source: join(publicPath, 'less'), dest: join(publicPath, 'css') }));

// Basic usage: LESS files in /public will be compiled to /public
app.use(lessMiddleware(publicPath, {
  debug: process.env.NODE_ENV !== 'production',
  force: process.env.NODE_ENV !== 'production', // Recompile on each request in dev
  once: process.env.NODE_ENV === 'production', // Recompile once per server restart in prod
  render: {
    compress: process.env.NODE_ENV === 'production'
  }
}));
app.use(express.static(publicPath));

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
  console.log(`LESS files in ${publicPath} will be compiled and served.`);
  console.log(`Try creating a 'styles.less' in ${publicPath} and access '/styles.css'`);
});

view raw JSON →