ArticleZip > Load Variables Into Less Css Preprocessor From Json File

Load Variables Into Less Css Preprocessor From Json File

If you're diving into the world of Less CSS preprocessor, you may have encountered situations where you need to load variables from an external JSON file. This can be a game-changer in terms of organizing your styles and making them more maintainable. In this article, we will walk you through the steps of loading variables into Less CSS from a JSON file.

First things first, you'll need to have Node.js installed on your machine to make use of the built-in file system module. If you haven't already, head over to the Node.js website and follow the installation instructions for your operating system.

Next, create a new JSON file, let's call it `variables.json`, and populate it with your desired variables in the following format:

Json

{
  "primaryColor": "#3498db",
  "secondaryColor": "#2ecc71",
  "baseFontSize": "16px",
  "borderRadius": "4px"
}

Save this file in the root directory of your project or in a folder where your Less files reside.

Now, create a new JavaScript file, for example, `loadVariables.js`, in the same directory as your JSON file. We will use this script to read the JSON file and generate Less code from it.

In `loadVariables.js`, you can use the following code snippet to read the JSON file and output the Less variables:

Javascript

const fs = require('fs');

const data = fs.readFileSync('variables.json');
const variables = JSON.parse(data);

let lessCode = '';

for (const variable in variables) {
  lessCode += `@${variable}: ${variables[variable]};n`;
}

fs.writeFileSync('variables.less', lessCode);

console.log('Variables loaded successfully into variables.less file.');

Save this script and open a terminal in the directory where the script is located. Run the script using Node.js by typing `node loadVariables.js`. This will generate a `variables.less` file in the same directory with all your variables defined in Less format.

Lastly, make sure to include the generated `variables.less` file in your main Less file by adding the following line:

Less

@import 'variables.less';

Now, you can use these variables throughout your Less stylesheets. For example:

Less

body {
  background-color: @primaryColor;
  font-size: @baseFontSize;
  border-radius: @borderRadius;
}

By loading variables from a JSON file into Less CSS, you can easily manage and update your styles without digging through lengthy stylesheets. This approach promotes reusability and maintainability in your projects. Have fun experimenting with different variables and taking your styling to the next level!