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

6
我正在尝试将参数传递给由gulp-watch调用的任务。我需要它,因为我正在尝试构建一个模块化框架。
  • 所以,如果在模块1中更改了文件,则不需要重新构建其他模块。
  • 而且我只想创建一个函数来为每个模块创建连接和压缩文件。
这是我到目前为止得到的:
//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
});

很多文档和示例似乎已经过时了(gulp.run(),gulp.start())。希望有人能在这里帮助我。
2个回答

8

我曾经遇到过同样的问题,花了一段时间进行搜索,最终找到了最简洁的方法,使用gulp.watch().on()事件处理程序和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';
    });
});

gulp-util 在需要从shell中传递(全局)参数时非常有用:

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

希望这能帮助其他人!祝好!
敬礼。

0

我将直接回答问题“如何将参数传递给gulp-watch调用的任务”。

我的做法,也是我看到的可能性之一,是使用全局变量在两个块之间传递值。你可以在观察者中启动任务之前设置它。然后,在任务中,在开始时将其传递给本地变量

有关更多详细信息,请参见此答案:https://dev59.com/FI_ea4cB1Zd3GeqPMEiI#49733123

在你想要实现的功能中,你也可以只使用一个监视器来监视包含所有模块的目录。如果是这样的结构,那么当发生更改时,你可以恢复更改后的文件路径。从而可以推断出属于哪个模块。通过获取模块文件夹。这样,你就不需要为每个新模块添加一个新的监视器。当有多个贡献者参与项目时,这可能非常方便,例如在开源项目中工作时。你只需要做一次,就不必再添加任何内容。就像委托原则一样,在处理多个元素的DOM事件处理时。即使所选择的结构并不将所有模块放在一个目录中,你也可以向一个监视器传递多个通配符。
gulp.watch(['glob1/**/*.js', 'glob2/**/*.js',...], function(evt) {/*.....*/});

根据你现有的结构,你可以逐步推断出模块是什么。

对于在场的观察者,我建议你这样做:

  watch('./your/allModulesFolder/**/*.js', function (evt) {
    rebuildModulWatchEvt = evt; //here you update the global var
    gulp.start('rebuildModul'); // you start the task
})

这里的evt包含多个信息:cwd、base、state、_contents等等。我们感兴趣的是path。因此,evt.path将给出所更改文件的路径。
在您的任务中,您可以选择执行以下任一操作:
gulp.task('rebuildModul', function() {
     let evt = rebuildModulWatchEvt; // at all start you pass it to a local var
     let filePath = evt.path; // how you get the changed file path
     // your code go here for the rest, following your structure, get the path for the module folder
});

或者你可以使用一个函数:

gulp.task('rebuildModul', function() {
     rebuildModulTaskRun(rebuildModulWatchEvt);
});
function rebuilModulTaskRun(evt) {
      let filePath = evt.path;
      // your code go here for the rest, following your structure, get the path for the module folder
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接