如何将参数传递给gulp-watch调用的任务

Chr*_*man 5 gulp gulp-watch

我试图将参数传递给gulp-watch正在调用的任务.我需要它,因为我正在尝试构建一个模块化框架.

  • 因此,如果模块1中的文件发生更改,则不需要重建其他模块.
  • 我只想要一个函数来创建每个模块的concatted和uglified文件.

这是我到目前为止所得到的:

//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
});
Run Code Online (Sandbox Code Playgroud)

许多文档/示例似乎已经过时(gulp.run(),gulp.start()).

我希望有人可以帮助我.

小智 7

我有同样的问题,搜索了一段时间,并且我提出了"最干净"的方式,使用了.on()事件处理程序gulp.watch()gulp-util.env属性:

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';
    });
});
Run Code Online (Sandbox Code Playgroud)

如果你需要从shell传递(全局)参数,gulp-util也会派上用场:

 [emiliano@dev ~]# gulp script --module=module1 --minify
Run Code Online (Sandbox Code Playgroud)

希望这有助于其他人!

问候.