Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter to gulp-watch invoked task

I am trying to pass a parameter to a task that is being invoked by gulp-watch. I need it because I am trying to build a modular framework.

  • So if a file changes in module 1, the other modules don't need to be rebuild.
  • And I want just one function to create the concatted & uglified files per module.

This is what I got so far:

//here I need the 'module' parameter
gulp.task('script', function(module) { ... }

gulp.task('watch', function() {
    gulp.watch('files/in/module1/*.js', ['script']); //here I want to pass module1
    gulp.watch('files/in/module2/*.js', ['script']); //here I want to pass module2
});

A lot of the documentation/examples seems to be outdated (gulp.run(), gulp.start()).

I hope someone can help me out here.

like image 359
Chris Laarman Avatar asked Mar 01 '15 23:03

Chris Laarman


1 Answers

I had the very same issue, searched for a while, and the "cleanest" way I came up with, uses the .on() event handler of gulp.watch(), and the .env property of gulp-util:

var gulp = require('gulp');
$.util = require('gulp-util');

var modules = {
    module1: {}, // awesome module1
    module2: {}  // awesome module2
};

gulp.task('script', function(){
    var moduleName = $.util.env.module;
    // Exit if the value is missing...
    var module = modules[moduleName];
    if (!module) {
        $.util.log($.util.colors.red('Error'), "Wrong module value!");
        return;
    }
    $.util.log("Executing task on module '" + moduleName + "'");
    // Do your task on "module" here.
});


gulp.task('watch', function () {
    gulp.watch(['files/in/module1/*.js'], ['script']).on('change', function () {
        $.util.env.module = 'module1';
    });
    gulp.watch(['files/in/module2/*.js'], ['script']).on('change', function () {
        $.util.env.module = 'module2';
    });
});

gulp-util also comes in handy if you need to pass (global) parameters from the shell:

 [emiliano@dev ~]# gulp script --module=module1 --minify

Hope this helps someone else out there!

Regards.

like image 92
Emiliano Esposito Avatar answered Nov 14 '22 11:11

Emiliano Esposito