Less.js Programmatic Usage
Last Updated :
22 Dec, 2023
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:
- Input(String): The less code that you want to compile.
- Optional(Object): This is containing various configuration options for the compilation process.
- Callback(Function): This function is to handle the result of the compilation.
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.
HTML
<!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=
"https://cdnjs.cloudflare.com/ajax/libs/less.js/3.12.2/less.min.js"></script>
</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-1The 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.
HTML
<!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=
"https://cdnjs.cloudflare.com/ajax/libs/less.js/3.12.2/less.min.js"></script>
</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-2Getting 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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read