Stephen Sorensen
Stephen Sorensen

Reputation: 11945

How do I process one src file multiple ways using gulp?

I want to use one source file to generate multiple destination files with different characteristics. Here's a watered down version of what I want to do:

gulp.task('build', function() {
  var src = gulp.src('myfile.txt')

  for (var i = 0; i < 10; i++) {
    src
      .pipe(someplugin(i))
      .pipe(rename('myfile-' + i + '.txt'))
      .dest('./build')
  }
});

Presumably, "someplugin" would change the file contents based on the index passed to it, so the code above would generate 10 files, each with slightly different content.

This doesn't work, and I didn't expect it to, but is there another way to achieve this?

Upvotes: 2

Views: 392

Answers (2)

Stephen Sorensen
Stephen Sorensen

Reputation: 11945

I ended up creating a function that builds my tasks for me. Here's an example:

function taskBuilder(i) {
  return function() {
    gulp.src('*.mustache')
      .pipe(someplugin(i))
      .pipe(rename('myfile-' + i + '.txt'))
      .dest('./build');
  };
}

var tasks, task, i;
for (i = 0; i < 10; i++) {
  taskName = 'tasks-' + i;
  gulp.task(taskName, taskBuilder(i));
  tasks.push(task);
}

gulp.task('default', tasks);

Upvotes: 2

soenguy
soenguy

Reputation: 1371

Maybe you should check this :

How to save a stream into multiple destinations with Gulp.js?

If it doesn't answer your question, I believe a simple solution would be to have many tasks all running one after the other. For example :

gulp.task('build', function() {
  return gulp.src('*.txt')
      .pipe(someplugin(i))
      .pipe(rename('myfile-1.txt'))
      .dest('./build')
  }
 });

gulp.task('build2', [build], function() {
  return gulp.src('*.txt')
      .pipe(someplugin(i))
      .pipe(rename('myfile-2.txt'))
      .dest('./build')
  }
});

Running task 'build2' will run 'build' first, and then 'build2' when it's complete. If you don't have to wait for 'build2' to be finished, just remove the "return" and they will run at the same time.

Upvotes: 1

Related Questions