Less - Programmatic Usage
Less - Programmatic Usage
Section titled “Less - Programmatic Usage”Less can be compiled programmatically within Node.js environments, which is essential for integrating it into build systems and automated workflows. The core function for this is less.render.
Using less.render
Section titled “Using less.render”The less.render function takes your Less code as a string, an optional options object, and can be used with Promises (recommended) or a callback.
Promise-based (Recommended):
Section titled “Promise-based (Recommended):”less.render(lessInputString, options) .then(function(output) { // output.css = string of compiled CSS // output.map = string of sourcemap (if generated) // output.imports = array of imported filenames console.log(output.css); }) .catch(function(error) { // error object with message, line, column, etc. console.error(error); });With async/await for cleaner asynchronous code:
async function compileLess(lessInputString, options) { try { const output = await less.render(lessInputString, options); console.log('CSS:', output.css); if (output.map) { console.log('Source Map:', output.map); } // Use output.css and output.map } catch (error) { console.error('Less Compilation Error:', error); }}Callback-style:
Section titled “Callback-style:”less.render(lessInputString, options, function(error, output) { if (error) { console.error(error); return; } // output.css, output.map, output.imports console.log(output.css);});Parameters
Section titled “Parameters”lessInputString: A string containing the Less code to compile.options: An optional object to configure the compilation process. Key options include:filename: (String) The filename of the input Less code. Crucial for error reporting, resolving relative@importpaths, and source map generation.paths: (Array of Strings) Paths to look for@imported files.plugins: (Array) Less plugins to use.sourceMap: (Object) Options for source map generation (e.g.,sourceMapFileInline: trueto embed the map in CSS).javascriptEnabled: (Boolean) Set tofalseto disable inline JavaScript execution in Less files (recommended for security).math: (String) Set math strictness, e.g.strict(formerlystrictMath: true). See command-line options for details.
Custom Logger
Section titled “Custom Logger”To capture logging messages from the Less compiler (e.g., warnings, debug info), you can add a custom logger:
less.logger.addListener({ debug: function(message) { console.debug('[LESS DEBUG]', message); }, info: function(message) { console.info('[LESS INFO]', message); }, warn: function(message) { console.warn('[LESS WARN]', message); }, error: function(message) { console.error('[LESS ERROR]', message); }});The listener functions (debug, info, warn, error) are all optional. If a compilation error occurs and is not handled by a custom error logger, it will be passed to the error callback or reject the Promise returned by less.render.
Example: Compiling a File
Section titled “Example: Compiling a File”Here’s a basic example of reading a Less file and compiling it:
// Assuming 'less' and 'fs' (Node.js file system module) are required// const less = require('less');// const fs = require('fs').promises;
async function compileMyLessFile(filePath, outputPath) { try { const lessInput = await fs.readFile(filePath, 'utf8'); const options = { filename: filePath, // Important for imports and error reporting sourceMap: { sourceMapFileInline: true // Example: Embed sourcemap in CSS } }; const output = await less.render(lessInput, options); await fs.writeFile(outputPath, output.css, 'utf8'); console.log(`Successfully compiled ${filePath} to ${outputPath}`); // if (output.map && !options.sourceMap.sourceMapFileInline) { // await fs.writeFile(outputPath + '.map', output.map, 'utf8'); // } } catch (error) { console.error('Less compilation error details:', error); // For more structured error output: // console.error(`Message: ${error.message}`); // console.error(`File: ${error.filename}:${error.line}:${error.column}`); }}
// Usage:// compileMyLessFile('src/styles.less', 'dist/styles.css');Real-world Scenarios & Further Reading
Section titled “Real-world Scenarios & Further Reading”- Build Systems: Programmatic usage is key for integrating Less into modern build tools like Webpack (with
less-loader), Gulp (withgulp-less), or Parcel (which often has out-of-the-box Less support). These tools manage compilation, watching files, and other asset processing. - Dynamic Theming: Server-side applications can use programmatic Less compilation to generate CSS dynamically based on user preferences or other runtime data (e.g., by passing variables through the
globalVarsormodifyVarsoptions inless.render). - Error Handling: Robust error handling in your
catchblock or error callback is important to provide useful feedback during development. The error object from Less contains detailed information like filename, line number, and column. - Official API Documentation: For the most up-to-date and detailed information on all options and capabilities, refer to the official Less API documentation: http://lesscss.org/usage/#programmatic-usage