Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile LESS with different variables using grunt

I have HTML template based on Bootstrap, that have different colors (red, green, etc.). Colors are changing using @brand variable in variables.less. Now I go to this file, change variable, compile less files, go to compiled css files directory and rename CSS file according it's color (red.css, green.css, etc.). And I make this steps 7 times (7 colors = 7 steps).

Can I automate this process using grunt or something like this and how?

like image 781
acidernt Avatar asked Aug 08 '14 08:08

acidernt


2 Answers

Using grunt-contrib-less you can overwrite any variable. So you can automate your process by doing something like the following -

module.exports = function(grunt) { 
    grunt.initConfig({  

        less: {

                /** Red**/
                red: {
                    options: {
                        paths: ["less/"],
                        modifyVars: {
                            brand : 'red'
                        }
                    },
                    files: {
                        "css/red.css": "less/style.less"
                    }
                },
                /** Red**/
                green: {
                    options: {
                        paths: ["less/"],
                        modifyVars: {
                            brand : 'green'
                        }
                    },
                    files: {
                        "css/green.css": "less/style.less"
                    }
                },
    });

    grunt.loadNpmTasks('grunt-contrib-less');


    grunt.registerTask('default', ['less:red','less:green']);
}

change the config based on your file structures and add as many item as you need - I made 2 items

like image 70
Aajahid Avatar answered Jan 03 '23 13:01

Aajahid


When dynamically generating your your task you can create a more DRY version of the accepted answer by @Aajhid, see also: Run Grunt tasks recursively over array

Your Gruntfile.js can look as follows:

module.exports = function (grunt) {
  'use strict';

var TaskArray = [];
var tasks = [];
var colors = ['red','green','blue'];

colors.forEach(function(color) { 
        tasks[color] = {options: {sourceMap:true, modifyVars:{}},files:{} };
        tasks[color]['options']['modifyVars']['brand']= color;
        tasks[color]['files']['dist/' + color + '.css'] = 'less/project.less';
        TaskArray.push('less:' + color);
}); 
grunt.loadNpmTasks('grunt-contrib-less');
grunt.config('less',tasks);
grunt.registerTask( 'default', TaskArray );  
}; 
like image 40
Bass Jobsen Avatar answered Jan 03 '23 15:01

Bass Jobsen