Search code examples
gulpconcatenationuglifyjs

Send uglify parameter for certain flow in gulp


Problem: Having multiple tasks for uglifying different javascript bundles and wanting to uglify this only on production with his own deploy task.

Solutions: Too much verbosity to define every task by itself. Using yargs for getting the parameters is also a too difficult approach for this problem.


Solution

  • Thought about this for a while, and came up with the perfect solution for myself.

    For instance I have this gulp task that concatenates javascript files:

    gulp.task('concat', function() {
      var stream = gulp
        .src('public/js/**/*.js')
        .pipe(concat('bundle.js'));
      if (ugly) {
        stream
          .pipe(uglify());
      }
      return stream
        .pipe(gulp.dest('public/dist'));
    });
    

    As you can see I check if the ugly variable is set within the task, so all I have to do is to create a task that is triggered before the concat task and sets the ugly variable to true.

    You could make such a function, do make sure the ugly variable is accessible to the scope of both task functions.

    var ugly;
    gulp.task('set-ugly', function() {
      ugly = true;
    });
    

    Last but not least the gulp deploy task, with as first task set-ugly.

    gulp.task('deploy', ['set-ugly', 'concat']);
    

    You can also use this approach for any other variable that you need to use within a task.