Syed
Syed

Reputation: 16543

How to pass array in GULP task in loop

I am not sure on to make the below given code to work:

var language = ['en', 'sp'];

gulp.task('jsonResourcesConcat', function() {
  return gulp.src('path/to/json/' + language + '/resources.json')
    .pipe(insert.prepend('window.resourcesData.' + language + ' = '))
    .pipe(concat('resources-' + language +'.js'))
    .pipe(gulp.dest('./www/assets/json2js/'));
});

I need the file should be output to folder ./www/assets/json2js/ with file names 'resources-en.js' and 'resources-sp.js'

Upvotes: 0

Views: 2276

Answers (1)

MarcoL
MarcoL

Reputation: 9989

Ok, let's start from your script:

var languages = ['en', 'sp'];

// this is the function that does all the work
function buildJson(language) {
  return gulp.src('path/to/json/' + language + '/resources.json')
    .pipe(insert.prepend('window.resourcesData.' + language + ' = '))
    .pipe(concat('resources-' + language +'.js'))
    .pipe(gulp.dest('./www/assets/json2js/'));
});

Now install the EventStream module to handle streams easily:

$ npm install event-stream

And use it to pipe Gulp streams

var es = require('event-stream');

// now define the gulp task
gulp.task('jsonResourcesConcat', function gulpTask(){
  // build the streams
  var streams = languages.map( buildJson );

  // now merge the streams together
  // see the doc here: https://www.npmjs.com/package/event-stream#merge-stream1streamn-or-merge-streamarray
  return es.merge( streams );
});

A similar answer can also be found here: How to batch similar gulp tasks to reduce code repetition

Upvotes: 7

Related Questions