Compile LESS to multiple CSS files, based on varia

2019-02-21 04:18发布

Having a single variable that specifies a color within a variables.less file (e.g. @themeColor: #B30F55;), and a .json file that constitutes a list of entities, where each key is an entity ID and the value of the key is that entity's color (e.g. '8ab834f32' : '#B30F55', '3cc734f31' : '#99981F'), how could I run a Grunt task that outputs as many independent CSS files as there are entities in the json, after substituting the variable value?

标签: css gruntjs less
1条回答
戒情不戒烟
2楼-- · 2019-02-21 05:11

You can define a different task for each color. grunt-contrib-less supports the Modifyvars option:

modifyVars

Type: Object Default: none

Overrides global variables. Equivalent to --modify-vars='VAR=VALUE' option in less.

You can set modifyVars: themeColor={yourcolor} for each task

.json file that constitutes a list of entities

See: Grunt - read json object from file

An other example can be found at Dynamic Build Processes with Grunt.js

example

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

than run grunt:

Running "less:8ab834f32" (less) task File dist/css/8ab834f32.css created: 24 B → 24 B

Running "less:3cc734f31" (less) task File dist/css/3cc734f31.css created: 24 B → 24 B

Done, without errors.

cat dist/css/3cc734f31.css:

p {
  color: #99981f;
}
查看更多
登录 后发表回答