Compile LESS to multiple CSS files, based on variable value

孤街醉人 提交于 2019-12-04 02:31:55

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/26751574/compile-less-to-multiple-css-files-based-on-variable-value

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