Compile LESS with different variables using grunt

眉间皱痕 提交于 2020-01-13 03:47:33

问题


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?


回答1:


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




回答2:


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 );  
}; 


来源:https://stackoverflow.com/questions/25198682/compile-less-with-different-variables-using-grunt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!