Installing and compiling
Less is installed as an npm package and run with the lessc command (Less compiler). The command reads a .less file and writes the finished .css. You need Node.js 20 or newer.
Installing
Create a folder for the site and install Less into it as a development dependency:
mkdir site
cd site
npm init -y
npm install --save-dev less
npx lessc --versionnpm init -y creates package.json, and the last command prints the version, for example lessc 4.9.1 (Less Compiler) [JavaScript]. npx runs lessc from the project's node_modules folder.
Project structure
The sources live in styles/, the compiled file in css/, and the page links only the CSS:
site/
├── index.html
├── css/
│ └── main.css ← created by lessc
├── styles/
│ └── main.less ← edited by you
└── package.jsonCreate styles/main.less:
// styles/main.less
@radius: 8px;
.card {
padding: 16px;
border-radius: @radius;
}Compiling
The command takes the source file and the output file:
npx lessc styles/main.less css/main.csscss/main.css appears:
.card {
padding: 16px;
border-radius: 8px;
}Link it in index.html as usual: <link rel="stylesheet" href="css/main.css">. Without the second argument lessc prints the CSS straight to the terminal — handy for a quick check.
npm scripts
To avoid typing the long command, put it into the scripts section of package.json:
{
"scripts": {
"build:css": "lessc styles/main.less css/main.css"
}
}Now npm run build:css is enough.
Watching for changes
lessc has no watch mode like sass --watch. The small chokidar-cli package adds one: it watches files and runs a command on every save.
npm install --save-dev chokidar-cli{
"scripts": {
"build:css": "lessc styles/main.less css/main.css",
"watch:css": "chokidar \"styles/**/*.less\" -c \"npm run build:css\" --initial"
}
}Run npm run watch:css: the --initial flag builds the CSS right away, and then every save of any .less file in styles/ rebuilds css/main.css. Stop watching with Ctrl+C.
Useful flags
| Flag | What it does |
|---|---|
--source-map | Writes a source map main.css.map next to the CSS |
--lint | Only checks the syntax, writes no CSS |
--math=always | Turns on the old division behaviour (see the lesson on operations) |
A source map tells the developer tools which line of the .less file a rule came from.
Common mistake
The command lessc styles/main.less without an output file saves nothing — it only prints the CSS to the terminal. If the page does not change, check that the command includes css/main.css.