javascript – Gulp:如何按顺序编写任务?

栏目: Node.js · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/30975483/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.使用运行顺序

您还可以使用 run-sequence 顺序运行任务数组:

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

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

3.使用lazypipe

虽然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'));
});

翻译自:https://stackoverflow.com/questions/30975483/gulp-how-to-compose-tasks-sequentially


以上所述就是小编给大家介绍的《javascript – Gulp:如何按顺序编写任务?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to the Analysis of Algorithms

An Introduction to the Analysis of Algorithms

Robert Sedgewick、Philippe Flajolet / Addison-Wesley Professional / 1995-12-10 / CAD 67.99

This book is a thorough overview of the primary techniques and models used in the mathematical analysis of algorithms. The first half of the book draws upon classical mathematical material from discre......一起来看看 《An Introduction to the Analysis of Algorithms》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具