Running Grunt tasks recursively over an array

I need to create multiple css files for different locations and browsers, all indicated by a flag in the filename. For example:

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

Differences in content are handled by booleans LESS @isIE, @isEN, @isJA, @isDE, etc., which follow the file naming pattern.

I would like to automate the build of these different versions by passing Grunt an array of flags and then for each:

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

This answer contains iterations , but is there a finer method?

+1


source to share


1 answer


Based on How to set up sourceMaps for LESS using Grunt if you have more than one file in your project? and Compile Less than a few CSS files based on the value of a variable , you can build yours Gruntfile.js

like this:

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 using an array languages

. Your boolean variables are modified by the modifyVars

grunt-contrib-less parameter, see also http://lesscss.org/usage/#using-less-in-the-browser-modify-variables .

When yours 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();

      

The startup grunt && cat dist/nl.css

should output as shown below:

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 */

      

+1


source







All Articles