css - 根据变量值将 LESS 编译成多个 CSS 文件

标签 css gruntjs less

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/

相关文章:

css - 在 LESS CSS 中动态定义一个变量

angularjs - webpack 和 less 如何在 css 中包含图像 url

html - 当我没有标签文本时,如何避免我的标签在我的自定义复选框中折叠?

javascript - 在边界线的位置插入空格

node.js - grunt bower-install 填充的 bower 依赖项

gruntjs - 如何让Yeoman持续运行测试

Javascript - 在部署时加载新的缓存

html - 换行后悬挂对齐/缩进<br>?

javascript - 在React项目中, "this"转换为 "undefined"

css - 是否可以在不在服务器上安装任何东西的情况下使用 CSS 嵌套规则?