LESS.js Middleware for Connect/Express
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
-
Error: .less file could not be found or processed.
cause The middleware could not locate the specified .less source file or an imported .less file.fixVerify the `source` option points to the correct directory containing your .less files. Check file paths, capitalization, and ensure read permissions. Use `debug: true` in options for more verbose logging about file resolution. -
TypeError: app.use is not a function
cause This error indicates that `app` is not an Express/Connect application instance, or `app.use` is being called before `app` is properly initialized.fixEnsure you have correctly initialized your Express or Connect application, e.g., `const express = require('express'); const app = express();` before calling `app.use(lessMiddleware(...));`. -
Error: 'less' not found. Is it installed?
cause The `less` package, which is a peer/runtime dependency, is not installed in your project.fixInstall the `less` package: `npm install less --save`. Ensure its version is compatible with your `less-middleware` version.
Warnings
- breaking Version 3.0.0 upgraded Less to version 3.x. This introduced potential breaking changes due to Less.js's own major version update, especially regarding syntax and features removed or altered in Less 3.
- breaking Version 2.0.0 introduced significant breaking changes due to an update to Less 2.4. The `options.parser` property was removed, and rendering options are now passed directly via `options.render`.
- gotcha Incorrect configuration of `dest` or `pathRoot` can lead to compiled CSS files not being found or written to unexpected locations. If `dest` is not specified, it defaults to the `source` directory, which may not be desirable in production for separation of concerns.
- gotcha Caching behavior (`force`, `once`, `cacheFile`) requires careful consideration for both development and production. In development, `force: true` is often desired for immediate feedback on style changes, but in production, `once: true` or `cacheFile` for faster startup is critical. Misconfiguration can lead to slow rebuilds or outdated CSS being served.
Install
-
npm install less-middleware -
yarn add less-middleware -
pnpm add less-middleware
Imports
- lessMiddleware
import { lessMiddleware } from 'less-middleware';import lessMiddleware from 'less-middleware'; // For ESM-compatible setups
- lessMiddleware
const lessMiddleware = require('less-middleware');
Quickstart
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'`);
});