基于变量值将LESS编译为多个CSS文件 [英] Compile LESS to multiple CSS files, based on variable value

查看:480
本文介绍了基于变量值将LESS编译为多个CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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


modifyVars

modifyVars

对象默认值:无

覆盖全局变量。

可以设置<$ c对于每个任务

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


.json文件,$ c> modifyVars:themeColor = {yourcolor} 实体

请参阅: Grunt - 从文件中读取json对象

另一个示例可以在使用Grunt.js的动态构建过程

示例

colors.json:

colors.json:

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

Gruntfile.js:

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

少/ main.less:

less/main.less:

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

比运行 grunt


运行less:8ab834f32(少)任务文件dist / css / 8ab834f32.css
created:24 B→ 24 B

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

运行less:3cc734f31(少)任务文件dist / css / 3cc734f31.css
created:24 B→24 B

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

完成,没有错误。

cat dist / css / 3cc734f31.css:

cat dist/css/3cc734f31.css:

p {
  color: #99981f;
}

这篇关于基于变量值将LESS编译为多个CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆