Gulp:如何顺序撰写任务?
我需要通过顺序处理不同的来源来构build吞吐任务,因为它们之间存在依赖关系。
基于文档,这应该做我的合并stream,但我看不出如何执行命令和序列化他们。
在Gulp 3中对此进行build模的正确方法是什么?
我通常使用函数作为各个构build步骤的容器,然后从构build和监视任务中调用它们:
function buildModule(module) { var streams = []; // step one streams.push( gulp.src(path.join('./modules', module, '*.js')) // ... series of chained calls ); // step two streams.push( gulp.src([TMP, ...]) // generate target also using some of the files from step one ); return eventStream.merge(streams); } gulp.task('build:A', [], function () { return buildModule('A'); }); gulp.task('watch:buildModule', [], function () { gulp.watch('./modules/**/*.js', function (event) { if (event.type === 'changed') { return buildModule(path.basename(path.dirname(event.path))); } }); }); gulp.task('default', ['watch:buildModule'], function () {});
基本上有三种方法可以做到这一点。
1.定义依赖任务
Gulp允许开发人员通过传递任务名称数组作为第二个参数来定义相关任务:
gulp.task('concat', function () { // ... }); gulp.task('uglify', ['concat'], function () { // ... }); gulp.task('test', ['uglify'], function () { // ... }); // Whenever you pass an array of tasks each of them will run in parallel. // In this case, however, they will run sequentially because they depend on each other gulp.task('build', ['concat', 'uglify', 'test']);
2.使用运行序列
您也可以使用run-sequence顺序运行一系列任务:
var runSequence = require('run-sequence'); gulp.task('build', function (cb) { runSequence('concat', 'uglify', 'test', cb); });
3.使用lazypipe
尽pipeLazypipe是一个创build可重用pipe道的库,但您可以用它来创build顺序任务。 例如:
var preBuildPipe = lazypipe().pipe(jshint); var buildPipe = lazypipe().pipe(concat).pipe(uglify); var postBuildPipe = lazypipe().pipe(karma); gulp.task('default', function () { return gulp.src('**/*.js') .pipe(preBuildPipe) .pipe(buildPipe) .pipe(postBuildPipe) .pipe(gulp.dest('dist')); });
这个小模块可能有助于: 串stream 。
只需将eventStream.merge(streams)
replace为:
var series = require('stream-series'); // ... return series(streams);