First prerequisite is install nodjes and node command works as seen below

To check node command works or not, please run 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

THis will creates package.json and node project

Add the less dependency with npm install command

npm install less -g

This installs less library globally and lessc command is ready to use

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

You can compile file using lessc compiler

Here is syntax

lessc input output

Input file is less file Output is 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 below command

lessc main.less main.css

It generates main.css file with following content

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

let’s add compile process to package scripts in nodeprojects

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

with following command, you can compile the files

npm run compile

Watch changes in a folder for less files in nodejs project

Like Sass, There is no option --watch.

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

First, Install using npm install command

npm install -g less-watch-compiler

with command line, you can use below

less-watch-compiler src dist

src is an input folder that contains less files dist folder contain 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 src folder and compiles to css and outputs to dist folder.