我正在尝试将参数传递给gulp-watch正在调用的任务。我需要它,因为我正在尝试构建一个模块化框架。
这是我到目前为止所得到的:
//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())。
我希望有人可以帮助我。
答案 0 :(得分:7)
我遇到了同样的问题,搜索了一段时间,并且我提出了“最干净”的方式,使用了.on()
的{{1}}事件处理程序和gulp.watch()
属性gulp-util:
.env
如果你需要从shell传递(全局)参数,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';
});
});
希望这可以帮助其他人!
问候。
答案 1 :(得分:0)
因为我将直接回答“如何传递参数以gulp-watch调用的任务”这个问题
我的做法和我看到的可能性之一是使用全局变量来传递两个块之间的值。你在观察者中启动任务之前设置它。并且在任务中,只需在开始时将其传递给本地变量。
有关详细信息,请参阅此答案:https://stackoverflow.com/a/49733123/7668448
在您想要实现的目标中,您只能在包含所有模块的目录上使用一个观察者。如果是这样的话。然后,当发生更改时,您可以恢复更改的文件路径。从那里你可以推断出属于哪个模块。通过获取Module文件夹。这样您就不需要为每个新模块添加新的观察程序。当有多个项目贡献者时,例如在开源上工作时,这可能会很好。你这样做了一次,而不必关心添加任何东西。就像委托原则一样,当有多个元素时使用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
}