Compile LESS with different variables using grunt
I have a Bootstrap based HTML template that has different colors (red, green, etc.). Colors are changed using a variable @brand
in variables.less
. Now I go to this file, change the variable, compile fewer files, go to the compiled css files directory and rename the CSS file to match that color ( red.css
, green.css
etc.). And I do this steps 7 times (7 colors = 7 steps).
Can I automate this process with grunt or something like this and how?
source to share
Using grunt-contrib-less you can overwrite any variable. Thus, you can automate your process by following these steps:
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 items as you need - I made 2 items
source to share
When dynamically creating your issue, you can create a drier version of @Aajhid's accepted answer, see also: Run Grunt tasks recursively over an array
Yours Gruntfile.js
might look like this:
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 );
};
source to share