The first prerequisite is to install NodeJS and the node command works as seen below.

To check node command works or not, please run the below command

C:\>node --version
v14.17.0

Create a node project from scratch

  • First create a directory or folder mkdir nodejsless
  • Change directory and run npm I command

It creates package.json and node projects.

Add the less dependency with the npm install command

npm install less -g

It installs less library globally and the lessc command is ready to use

B:\blog\nodejsless>lessc --version
lessc 4.1.2 (Less Compiler) [JavaScript]

You can compile the file using lessc compiler.

Here is syntax

lessc input output

The input file is less file Output is a CSS file

Let’s create a sample main.less file

@font-color:blue;

@link-color:@font-color;

h1{
color: @font-color
}
a{
color: @link-color
}

Compile the code using the below command

lessc main.less main.css

It generates a main.css file with the following content

h1 {
  color: blue;
}
a {
  color: blue;
}

let’s add compile process to package scripts in node projects

scripts:{
    "compile":"lessc main.less main.css"
}

with the following command, you can compile the files

npm run compile

Watch changes in a folder for less files in the nodejs project

Like Sass, There is no option --watch.

There is an npm less-watch-compiler library to compile and watch less files in a directory.

First, Install using the npm install command

npm install -g less-watch-compiler

with the command line, you can use below

less-watch-compiler src dist

src is an input folder that contains less files dist folder contains output CSS files

you can also add in script files of package.json

scripts:{
    "watchless":"less-watch-compiler src dist"
}

This looks for any changes in the src folder and compiles to CSS and outputs to the dist folder.