Run Grunt tasks recursively over array

2019-06-05 07:52发布

I have to build a number of css files for different locations and browsers all delineated by a flag in the file name. For instance:

  • styles-en.css
  • styles-jp.css
  • styles-ie.css

The content differences are handled by LESS boolean variables @isIE, @isEN, @isJA, @isDE etc. that match the file naming pattern.

I would love to automate building these different versions by passing Grunt an array of flags then for each:

  • set the variable for LESS
  • run LESS compiler for all files in a folder (same for all languages)
  • use the variable in the exported file name

This answer spells out the iterations but is there a tidier method?

标签: gruntjs less
1条回答
趁早两清
2楼-- · 2019-06-05 08:37

Based on How to configure sourceMaps for LESS using Grunt when there is more than one file in your project? and Compile LESS to multiple CSS files, based on variable value you can create your Gruntfile.js as follows:

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

The above dynamically creates your tasks by using the languages array. Your boolean variables are change by the modifyVars option of grunt-contrib-less, see also http://lesscss.org/usage/#using-less-in-the-browser-modify-variables.

When your less/project.less contains the following code:

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

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

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

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

.m();

Running grunt && cat dist/nl.css should output like that shown beneath:

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 */
查看更多
登录 后发表回答