在数组上递归运行Grunt任务

时间:2015-04-21 23:11:27

标签: gruntjs less

我必须为不同的位置和浏览器构建一些css文件,所有这些文件都由文件名中的标志描述。例如:

  • 样式-en.css
  • 样式-jp.css
  • 样式-ie.css

内容差异由与文件命名模式匹配的LESS布尔变量@ isIE,@ isen,@ isJA,@ isDE等处理。

我希望通过为每个传递Grunt标志数组来自动构建这些不同的版本:

  • 为LESS
  • 设置变量
  • 为文件夹中的所有文件运行LESS编译器(所有语言都相同)
  • 在导出的文件名中使用该变量

This answer spells out the iterations但有更简洁的方法吗?

1 个答案:

答案 0 :(得分:1)

根据How to configure sourceMaps for LESS using Grunt when there is more than one file in your project?Compile LESS to multiple CSS files, based on variable value,您可以按照以下方式创建Gruntfile.js

module.exports = function (grunt) {
  'use strict';

var TaskArray = [];
var tasks = [];
//var lessVariable = '';
var languages = ['de','en','nl'];

languages.forEach(function(language) { 
        tasks[language] = {options: {sourceMap:true, modifyVars:{}},files:{} };
        tasks[language]['options']['sourceMapFilename'] = 'dist/' + language + '.map.css';
        tasks[language]['options']['modifyVars']['is' + language.toUpperCase()]= true;
        tasks[language]['files']['dist/' + language + '.css'] = 'less/project.less';
        TaskArray.push('less:' + language);
}); 
grunt.loadNpmTasks('grunt-contrib-less');
grunt.config('less',tasks);
grunt.registerTask( 'default', TaskArray );  
}; 

以上使用languages数组动态创建任务。您的布尔变量由grunt-contrib-less的modifyVars选项更改,另请参阅http://lesscss.org/usage/#using-less-in-the-browser-modify-variables

当您的less/project.less包含以下代码时:

@isDE: false;
@isNL: false;
@isEN: false;

.m when (@isDE) {
language: de;
}

.m when (@isNL) {
language: nl;
}

.m when (@isEN) {
language: en;
}

.m();

正在运行grunt && cat dist/nl.css的输出方式如下所示:

Running "less:de" (less) task
File dist/de.map.css created.
File dist/de.css created

Running "less:en" (less) task
File dist/en.map.css created.
File dist/en.css created

Running "less:nl" (less) task
File dist/nl.map.css created.
File dist/nl.css created

Done, without errors.
.m {
  language: nl;
}
/*# sourceMappingURL=dist/nl.map.css */