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:如何按顺序编写任务?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Spring揭秘

Spring揭秘

王福强 / 人民邮电出版社 / 2009.8 / 99.00元

没有教程似的训导,更多的是说故事般的娓娓道来,本书是作者在多年的工作中积累的第一手Spring框架使用经验的总结,深入剖析了Spring框架各个模块的功能、出现的背景、设计理念和设计原理,揭开了Spring框架的神秘面纱,使你“知其然,更知其所以然”。每部分的扩展篇帮助读者活学活用Spring框架的方方面面,同时可以触类旁通,衍生出新的思路和解决方案。 本书内容全面,论述深刻入理,必将成为每......一起来看看 《Spring揭秘》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具