在 variables.less
文件中有一个指定颜色的变量(例如 @themeColor: #B30F55;
)和一个 .json
构成实体列表的文件,其中每个键是一个实体 ID,键的值是该实体的颜色(例如 '8ab834f32' : '#B30F55', '3cc734f31' : '#99981F'
),在替换变量值后,我如何运行输出与 json 中的实体一样多的独立 CSS 文件的 Grunt 任务?
最佳答案
您可以为每种颜色定义不同的任务。 grunt-contrib-less 支持 Modifyvars 选项:
modifyVars
Type: Object Default: none
Overrides global variables. Equivalent to --modify-vars='VAR=VALUE' option in less.
你可以为每个任务设置modifyVars: themeColor={yourcolor}
.json file that constitutes a list of entities
参见:Grunt - read json object from file
另一个示例可以在 Dynamic Build Processes with Grunt.js 找到
示例
颜色.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
:
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;
}
关于css - 根据变量值将 LESS 编译成多个 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26751574/