Gulp:如何将参数从手表传递到任务 [英] Gulp: how to pass parameters from watch to tasks
问题描述
使用 gulp 你经常会看到这样的模式:
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 ));
});
这是否实际上将监视的文件传递到模板任务中?这些如何覆盖/扩展/过滤 src'ed 任务?
Does this actually pass the watch'ed files into the templates task? How do these overwrite/extend/filter the src'ed tasks?
推荐答案
我前段时间也有同样的问题,经过一番挖掘得出以下结论.
I had the same question some time ago and came to the following conclusion after digging for a bit.
gulp.watch
是一个发出 change
事件的 eventEmitter,因此您可以这样做:
gulp.watch
is an eventEmitter that emits a change
event, and so you can do this:
var watcher = gulp.watch('src/*.jade',['templates']);
watcher.on('change', function(f) {
console.log('Change Event:', f);
});
你会看到这个:
Change Event: { type: 'changed',
path: '/Users/developer/Sites/stackoverflow/src/touch.jade' }
这个信息大概可以通过它的任务函数或 gulp.src
的行为传递给 template
任务.
This information could presumably be passed to the template
task either via its task function, or the behavior of gulp.src
.
任务函数本身只能接收回调(https://github.com/gulpjs/gulp/blob/master/docs/API.md#fn)并且无法接收有关乙烯基文件的任何信息(https://github.com/wearefractal/vinyl-fs).
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.
启动任务的源(在这种情况下为 .watch
,或 gulp 命令行)对 gulp.src('src-glob', [options] 的行为没有影响)代码>.
'src-glob'
是一个字符串(或字符串数组)和 options
(https://github.com/isaacs/node-glob#options) 没有任何文件更改.
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])
. 'src-glob'
is a string (or array of strings) and options
(https://github.com/isaacs/node-glob#options) has nothing about any file changes.
因此,我看不到 .watch
可以直接影响它触发的任务的行为.
Hence, I don't see any way in which .watch
could directly affect the behavior of a task it triggers.
如果您只想处理更改的文件,可以使用 gulp-changed
(https://www.npmjs.com/package/gulp-changed) 如果你想使用 gulp.watch
,或者你冷使用 gulp-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
.
或者,您也可以这样做:
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/'))
}
这篇关于Gulp:如何将参数从手表传递到任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!