Open In App

Less.js Programmatic Usage

Programmatic usage of Less.js involves utilizing the Less JavaScript API to compile Less code into CSS dynamically. This is commonly done in web development to generate stylesheets on the fly or to integrate Less.js into build processes.

Less.render Function

This function is provided by Less.js library. Which compiles Less code into CSS and allows for programmatic rendering of the stylesheet. It is also called the main entry point of Less.



Syntax:

less.render( input, [optional], [callback] );

Parameters:

If you wanted to render a file, you would first read it into a string (to pass to less.render) and then set the filename field on options to be the filename of the main file. less will handle all the processing of the imports.

Example 1: Example of using Less.render Function.






<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Less.js Example</title>
    <!-- Include Less.js library -->
    <script src=
</head>
 
<body>
    <h1>Less.js Example</h1>
    <script>
        // Add your Less code here
        const lessCode = `
      @primary-color: #3498db;
      body {
        color: @primary-color;
      }
    `;
 
        // Add the log listener
        less.logger.addListener({
            debug: function (msg) {
                console.log('Debug:', msg);
            },
            info: function (msg) {
                console.log('Info:', msg);
            },
            warn: function (msg) {
                console.warn('Warning:', msg);
            },
            error: function (msg) {
                console.error('Error:', msg);
            }
        });
 
        // Compile Less code
        less.render(lessCode, {}, (error, result) => {
            if (!error) {
                // Apply the compiled CSS to the page
                const style = document.createElement('style');
                style.textContent = result.css;
                document.head.appendChild(style);
                console.log('Compiled CSS:', result.css);
            } else {
                console.error('Compilation Error:', error);
            }
        });
    </script>
</body>
 
</html>

Output: To see the log messages, clicking on the page, selecting “Inspect,” and then navigating to the “Console” tab). There, you’ll see the log messages generated during the compilation process.

Output-1

The compiled CSS will set the color of the body element to #3498db.

Example 2: Aanother example of less.render function and In this example we will use variables and mixins.




<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
  <title>Less.render Example</title>
  <!-- Include Less.js library -->
  <script src=
</head>
<body>
  <h1>Less.render Example-2</h1>
  <script>
    // Your Less code with variables and mixins
    const lessCode = `
      @primary-color: #3498db;
 
      .box {
        background-color: lighten(@primary-color, 20%);
        padding: 10px;
        border: 1px solid darken(@primary-color, 10%);
      }
    `;
 
    // Compile Less code
    less.render(lessCode, {}, (error, result) => {
      if (!error) {
        // Apply the compiled CSS to a specific element
        const container = document.createElement('div');
        container.className = 'box';
        document.body.appendChild(container);
        console.log('Compiled CSS:', result.css);
      } else {
        console.error('Compilation Error:', error);
      }
    });
  </script>
</body>
</html>

Output: The compiled CSS for the .box class will set the background color and border color based on the primary color.

Output-2

Getting Access to the Log

A Log listener allows you to capture and handle log messages generated during the compilation processs. When you compile Less code using the less.render function, the compiler may produce log messages, such as warnings or errors.

Syntax:

const result = less.render(lessCode, options);
console.log(result);

Example: To add log listener in your code here is the example.

less.logger.addListener({
debug: function (msg) {
},
info: function (msg) {
},
warn: function (msg) {
},
error: function (msg) {
}
});

All functions are optional. An error will not be logged, but instead is passed back to the callback or promise in less.render.


Article Tags :