Run Grunt tasks recursively over array

一个人想着一个人 提交于 2020-01-14 04:33:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/29784810/run-grunt-tasks-recursively-over-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!