【问题标题】:Compile LESS to multiple CSS files, based on variable value根据变量值将 LESS 编译为多个 CSS 文件
【发布时间】:2014-11-05 07:13:44
【问题描述】:

variables.less 文件(例如@themeColor: #B30F55;)和构成实体列表的.json 文件中有一个变量来指定颜色,其中每个键是一个实体 ID 和键的值是该实体的颜色(例如'8ab834f32' : '#B30F55', '3cc734f31' : '#99981F'),在替换变量值后,我如何运行一个输出与 json 中的实体一样多的独立 CSS 文件的 Grunt 任务?

【问题讨论】:

    标签: css gruntjs less


    【解决方案1】:

    您可以为每种颜色定义不同的任务。 grunt-contrib-less 支持 Modifyvars 选项:

    修改变量

    类型:对象默认值:无

    覆盖全局变量。相当于 --modify-vars='VAR=VALUE' 更少的选项。

    您可以为每个任务设置modifyVars: themeColor={yourcolor}

    构成实体列表的.json文件

    见:Grunt - read json object from file

    另一个例子可以在Dynamic Build Processes with Grunt.js找到

    示例

    colors.json:

    {
    "colors" : [
    {"color" : "#B30F55", "name" : "8ab834f32"},
    {"color" : "#99981F", "name" : "3cc734f31"}
    ]
    }
    

    Gruntfile.js:

    module.exports = function (grunt) {
      'use strict';
    grunt.initConfig({
          pkg: grunt.file.readJSON('package.json'),
    });
    grunt.loadNpmTasks('grunt-contrib-less');
    var allTaskArray = [];
    var colors = grunt.file.readJSON('colors.json').colors;
    var tasks = {};   
    for (var color in colors) {
    var dest =  'dist/css/' + [colors[color].name] + '.css';
    tasks[colors[color].name] = {options: {
              strictMath: true,
              outputSourceFiles: true,
              modifyVars: {}
            },files:{} };
    tasks[colors[color].name]['files'][dest] = 'less/main.less';       
    tasks[colors[color].name]['options']['modifyVars']['color'] = colors[color].color;
    allTaskArray.push('less:' + colors[color].name);
    }   
    grunt.config('less',tasks);
    grunt.registerTask( 'default', allTaskArray );
    }; 
    

    less/main.less:

    @color: red;
    p{
    color: @color;
    }
    

    比运行grunt:

    运行“less:8ab834f32”(less)任务文件dist/css/8ab834f32.css 已创建:24 B → 24 B

    运行 "less:3cc734f31" (less) 任务文件 dist/css/3cc734f31.css 已创建:24 B → 24 B

    完成,没有错误。

    cat dist/css/3cc734f31.css:

    p {
      color: #99981f;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多