简体   繁体   English

Gulp:如何将参数从watch传递给任务

[英]Gulp: how to pass parameters from watch to tasks

With gulp you often see patterns like this: 有了吞咽,你经常会看到这样的模式:

gulp.watch('src/*.jade',['templates']);

gulp.task('templates', function() {
  return gulp.src('src/*.jade')
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('dist/'))
    .pipe( livereload( server ));
});

Does this actually pass the watch'ed files into the templates task? 这实际上是将watcheded文件传递给模板任务吗? How do these overwrite/extend/filter the src'ed tasks? 这些如何覆盖/扩展/过滤src的任务?

I had the same question some time ago and came to the following conclusion after digging for a bit. 我前段时间遇到了同样的问题,并在挖掘了一下之后得出了以下结论。

gulp.watch is an eventEmitter that emits a change event, and so you can do this: gulp.watch是一个发出change事件的eventEmitter,所以你可以这样做:

var watcher = gulp.watch('src/*.jade',['templates']);

watcher.on('change', function(f) {
  console.log('Change Event:', f);
});

and you'll see this: 你会看到这个:

Change Event: { type: 'changed',
  path: '/Users/developer/Sites/stackoverflow/src/touch.jade' }

This information could presumably be passed to the template task either via its task function, or the behavior of gulp.src . 可以通过其任务函数或gulp.src的行为将此信息传递给template任务。

The task function itself can only receive a callback ( https://github.com/gulpjs/gulp/blob/master/docs/API.md#fn ) and cannot receive any information about vinyl files ( https://github.com/wearefractal/vinyl-fs ) that are used by gulp. 任务函数本身只能接收回调( https://github.com/gulpjs/gulp/blob/master/docs/API.md#fn )并且无法接收有关乙烯基文件的任何信息( https://github.com gulp使用/ wearefractal / vinyl-fs )。

The source starting a task ( .watch in this case, or gulp command line) has no effect on the behavior of gulp.src('src-glob', [options]) . 启动任务的源(本例中为.watch.watch命令行)对gulp.src('src-glob', [options])的行为没有影响。 'src-glob' is a string (or array of strings) and options ( https://github.com/isaacs/node-glob#options ) has nothing about any file changes. 'src-glob'是一个字符串(或字符串数​​组), optionshttps://github.com/isaacs/node-glob#options )没有任何文件更改。

Hence, I don't see any way in which .watch could directly affect the behavior of a task it triggers. 因此,我没有看到任何方式.watch可以直接影响它触发的任务的行为。

If you want to process only the changed files, you can use gulp-changed ( https://www.npmjs.com/package/gulp-changed ) if you want to use gulp.watch , or you cold use gulp-watch . 如果你只想处理更改的文件,你可以使用gulp-changedhttps://www.npmjs.com/package/gulp-changed )如果你想使用gulp.watch ,或者你使用gulp.watch gulp-watch

Alternatively, you could do this as well: 或者,您也可以这样做:

var gulp = require('gulp');
var jade = require('gulp-jade');
var livereload = require('gulp-livereload');

gulp.watch('src/*.jade', function(event){
  template(event.path);
});

gulp.task('templates', function() {
  template('src/*.jade');
});

function template(files) {
  return gulp.src(files)
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('dist/'))
}

One of the possible way to pass a parameter or a data from your watcher to a task. 将参数或数据从观察者传递到任务的可能方法之一。 I s through using a global variable , or a variable that is in both blocks scops. 使用全局变量 ,或两个块scops中的变量。 Here is an example: 这是一个例子:

gulp.task('watch', function () {
        //....
        //json comments 
        watch('./app/tempGulp/json/**/*.json', function (evt) {
             jsonCommentWatchEvt = evt; // we set the global variable first
             gulp.start('jsonComment'); // then we start the task
        })
})

//global variable
var jsonCommentWatchEvt = null

//json comments task

gulp.task('jsonComment', function () {
    jsonComment_Task(jsonCommentWatchEvt)
})

And here the function doing the task work in case it interest any one, But know i didn't need to put the work in such another function i could just implemented it directly in the task. 在这里执行任务的函数工作以防任何人感兴趣,但是知道我不需要将工作放在这样的另一个函数中我可以直接在任务中实现它。 And for the file you have your global variable. 对于文件,您有全局变量。 Here it's jsonCommentWatchEvt . 这是jsonCommentWatchEvt But know if you don't use a function as i did, a good practice is to assign the value of the global variable to a local one, that you will be using. 但是要知道如果你不像我一样使用函数,一个好的做法是将全局变量的值赋给你将要使用的本地变量。 And you do that at the all top entry of the task. 而你在任务的所有顶部条目都这样做。 So you will not be using the global variable itself. 所以你不会使用全局变量本身。 And that to avoid the problem that it can change by another watch handling triggering. 这是为了避免它可以通过另一个手表处理触发而改变的问题。 When it stay in use by the current running task. 当它由当前运行的任务保持使用时。

function jsonComment_Task(evt) {
    console.log('handling : ' + evt.path);
    gulp.src(evt.path, {
        base: './app/tempGulp/json/'
    }).
    pipe(stripJsonComments({whitespace: false})).on('error', console.log).
    on('data', function (file) { // here we want to manipulate the resulting stream

        var str = file.contents.toString()

        var stream = source(path.basename(file.path))
        stream.end(str.replace(/\n\s*\n/g, '\n\n'))
        stream.
        pipe(gulp.dest('./app/json/')).on('error', console.log)
    })
}

I had a directory of different json's files, where i will use comments on them. 我有一个不同的json文件的目录,我将在其中使用注释。 I'm watching them. 我在看他们。 When a file is modified the watch handling is triggered, and i need then to process only the file that was modified. 修改文件后,将触发监视处理,然后我需要仅处理已修改的文件。 To remove the comments, i used json-comment-strip plugin for that. 要删除注释,我使用了json-comment-strip插件。 Plus that i needed to do a more treatment. 另外,我需要做更多的治疗。 to remove the multiple successive line break. 删除多个连续的换行符。 Whatever, at all first i needed to pass the path to the file that we can recover from the event parameter . 无论如何,首先我需要将路径传递给我们可以从事件参数中恢复的文件 I passed that to the task through a global variable, that does only that. 我通过一个全局变量传递给任务,只做那个。 Allow passing the data. 允许传递数据。

Note: Even though that doesn't have a relation with the question, in my example here, i needed to treat the stream getting out from the plugin processing. 注意:即使这与问题没有关系,在我的示例中,我需要处理从插件处理中流出的流。 i used the on("data" event. it's asynchronous. so the task will mark the end before the work completely end (the task reach the end, but the launched asynchronous function will stay processing a little more). So the time you will get in the console at task end, isn't the time for the whole processing, but task block end. Just that you know. For me it doesn't matter. 我使用了on("data"事件。它是异步的。所以任务将在工作完全结束之前标记结束(任务到达结束,但启动的异步函数将继续处理更多)。所以你需要的时间在任务结束时进入控制台,不是整个处理的时间,而是任务块结束。只是你知道。对我来说没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM