簡體   English   中英

Gulp:如何按順序編寫任務?

[英]Gulp: how to compose tasks sequentially?

我將需要通過順序處理不同的源來組成gulp任務,因為它們之間存在依賴性。

根據文檔,這應該在合並流中完成,但是我看不到如何強制執行命令和序列化它們。

在Gulp 3中對此建模的正確方法是什么?

我通常將函數用作各個構建步驟的容器,然后從構建中調用它們並監視任務:

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.使用運行順序

您還可以使用運行序列順序運行一系列任務:

var runSequence = require('run-sequence');

gulp.task('build', function (cb) {
    runSequence('concat', 'uglify', 'test', cb);
});

3.使用懶人

盡管Lazypipe是用於創建可重用管道的庫,但是您可以通過某種方式使用它來創建順序任務。 例如:

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-series

只需將eventStream.merge(streams)替換為:

var series = require('stream-series');
// ...
return series(streams);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM