Gulp:在另一个任务中使用一个任务的输出

Eri*_*icC 18 stream gulp

我有三个gulp任务,其中最后一个task(allScripts)首先运行两个相关任务,然后从它们加入结果文件.

在上一个任务中,我可以从两个第一个任务中删除两个结果文件,并且在使用连接文件之后幸福地生活.

但我在想,是否有可能通过某种方式allScripts"直接"将这些临时文件传递给任务?

gulp.task('firstGroup', function() {
  return gulp.src('some/files/*.js')
    .pipe(doSomething())
    .pipe(concat('some-scripts.js'))
    .pipe(gulp.dest('dest'));
});

gulp.task('secondGroup', function() {
  return gulp.src('some/other/files/*.js')
    .pipe(doSomethingElse())
    .pipe(concat('some-other-scripts.js'))
    .pipe(gulp.dest('dest'));
});

gulp.task('allScripts', ['firstGroup','secondGroup'], function() {
  return gulp.src(['dest/some-scripts.js','dest/some-other-scripts.js'])
    .pipe(concat('all-scripts.js'))
    .pipe(gulp.dest('dest'))
    // delete the two src-files
});
Run Code Online (Sandbox Code Playgroud)

MLM*_*MLM 17

如果一切都可以是单个任务,您可以使用该gulp-merge插件将多个流组合成一个.如果任务需要保持独立,下面还有一个解决方案,但请注意,该方法是一个黑客,因为它依赖于Gulp中的暴露属性.

如果没有黑客解决方案,使用另一个任务的输出,则需要中间存储,就像您对文件所做的那样.

单任务解决方案:

这是一个使用的准系统演示gulp-merge:

var gulp = require('gulp');
var gulpMerge = require('gulp-merge');
var concat = require('gulp-concat');
var replace = require('gulp-replace');

gulp.task('all-txt', function() {
    return gulpMerge(
            gulp.src('file1.txt')
                .pipe(replace(/foo/g, 'bar')),
            gulp.src('file2.txt')
                .pipe(replace(/baz/g, 'qux'))
        )
        .pipe(concat('all-text.txt'))
        .pipe(gulp.dest('dest'));
});
Run Code Online (Sandbox Code Playgroud)

在您的情况下,并使用您的问题中的代码,它看起来像:

var gulp = require('gulp');
var gulpMerge = require('gulp-merge');
var concat = require('gulp-concat');
// ... your plugins

gulp.task('allScripts', function() {
    return gulpMerge(
            gulp.src('some/files/*.js')
                .pipe(doSomething())
                .pipe(concat('some-scripts.js')),
            gulp.src('some/other/files/*.js')
                .pipe(doSomethingElse())
                .pipe(concat('some-other-scripts.js'))
        )
        .pipe(concat('all-scripts.js'))
        .pipe(gulp.dest('dest'));
});
Run Code Online (Sandbox Code Playgroud)

多任务解决方案:

如果您的任务结构不能使用上述方法将它们合并为单个任务,那么这是您最好的选择.从某种意义上说,它依赖于Gulp.tasks非标准的暴露属性,这有点令人讨厌.没有保证这将适用于未来版本的Gulp(目前使用Gulp v3.8.10进行测试).

这个代码片段依赖于event-stream它,因为它更强大,我在runTasksAndGetStreams函数中使用了它们的一些实用程序.

var gulp = require('gulp');

var concat = require('gulp-concat');
var replace = require('gulp-replace');
var es = require('event-stream');


gulp.task('all-txt', function() {
    return es.merge.apply(null, runTasksAndGetStreams(['file1-txt', 'file2-txt']))
        .pipe(concat('all-text.txt'))
        .pipe(gulp.dest('dest'));
});


gulp.task('file1-txt', ['random-task-dep'], function() {
    return gulp.src('file1.txt')
        .pipe(replace(/foo/g, 'bar'));
});

gulp.task('file2-txt', function() {
    return gulp.src('file2.txt')
        .pipe(replace(/baz/g, 'qux'));
});

gulp.task('random-task-dep', function() {
    return gulp.src('random-file.txt')
        .pipe(gulp.dest('dest'));
});



// Run the given tasks and returns their streams
// This will also take care of any task dependencies
//
// This is basically a custom gulp task orchestartor.
//
// Written for this SO question: http://stackoverflow.com/q/28334314/796832
// Gist: https://gist.github.com/MadLittleMods/d4083d2ba35e2f850161
//
// Params:
//      taskNames: string or array of strings of task names
//      debugLog: *optional* boolean to print some debug information to the console
function gulpRunTasksAndGetStreams(taskNames, /*optional*/debugLog) {
    // You can pass in a single task or an array of tasks to complete
    taskNames = [].concat(taskNames);

    // We polyfill the pieces of `gulp-util` that we use in case some one wants to use it without installing `gulp-util`
    var gutil;
    try {
        gutil = require('gulp-util');
    }
    catch(err) {
        gutil = {
            log: console.log,
            colors: {
                cyan: function(str) {
                    return str;
                },
                magenta: function(str) {
                    return str;
                }
            }
        };
    }

    var resultantTaskInfo = [];
    var taskMap = gulp.tasks;

    // Satisfy all of the task dependencies, create a placeholder stream, and collect the func 
    // to make the real stream to feed in later when the dependencies are done `mergedDepStream.on('end')`
    var mergedDepStream = null;
    taskNames.forEach(function(taskName) {
        var task = taskMap[taskName];

        if(debugLog) {
            gutil.log('root task:', gutil.colors.cyan(taskName), 'started working');
        }

        // Run any dependencies first
        var depStreamResult = runDependenciesRecursivelyForTask(taskName, taskMap);

        if(depStreamResult) {
            mergedDepStream = mergedDepStream ? es.merge(mergedDepStream, depStreamResult) : depStreamResult;
        }

        if(debugLog) {
            if(depStreamResult) {
                depStreamResult.on('end', function() {
                    gutil.log('root task:', gutil.colors.cyan(taskName), 'deps done');
                });
            }
            else {
                gutil.log('root task:', gutil.colors.cyan(taskName), 'no deps present');
            }
        }

        // Then push the task itself onto the list
        resultantTaskInfo.push({
            stream: es.through(),
            fn: task.fn
        });
    });

    // Once all of the dependencies have completed
    mergedDepStream.on('end', function() {

        if(debugLog) {
            gutil.log('All dependencies done, piping in real root tasks');
        }

        // Pipe the actual task into our placeholder
        resultantTaskInfo.forEach(function(taskInfo) {
            var actualTaskStream = taskInfo.fn();
            actualTaskStream.pipe(taskInfo.stream);
        });
    });


    // Recursively gets all of dependencies for a task in order
    function runDependenciesRecursivelyForTask(taskName, taskMap, mergedDependencyStream) {
        var task = taskMap[taskName];

        task.dep.forEach(function(depTaskName) {
            var depTask = taskMap[depTaskName];
            if(debugLog) {
                gutil.log('dep task:', gutil.colors.cyan(depTaskName), 'started working');
            }

            // Dependencies can have dependencies
            var recursiveStreamResult = null;
            if(depTask.dep.length) {
                recursiveStreamResult = runDependenciesRecursivelyForTask(depTaskName, taskMap, mergedDependencyStream);
                mergedDependencyStream = mergedDependencyStream ? es.merge(mergedDependencyStream, recursiveStreamResult) : recursiveStreamResult;
            }

            if(depTask.fn) {
                var whenStreamHandledCallback = function(/* we only use `noDeps` for logging */noDeps) {
                    if(debugLog) {
                        if(!noDeps) {
                            gutil.log('dep task:', gutil.colors.cyan(depTask.name), 'deps done');
                        }
                        else {
                            gutil.log('dep task:', gutil.colors.cyan(depTask.name), 'no deps present');
                        }
                    }

                    var depTaskStream = depTask.fn();
                    // Merge it in overall dependency progress stream
                    mergedDependencyStream = mergedDependencyStream ? es.merge(mergedDependencyStream, depTaskStream) : depTaskStream;
                };

                if(recursiveStreamResult === null) {
                    whenStreamHandledCallback(true);
                }
                else {
                    recursiveStreamResult.on('end', whenStreamHandledCallback);
                }
            }
        });

        return mergedDependencyStream;
    }


    // Return the (placeholder) streams which will get piped the real stream once the dependencies are done
    return resultantTaskInfo.map(function(taskInfo) {
        return taskInfo.stream;
    });
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ing 6

关于组合流,@ MLM有正确的想法.

但不要忘记Gulp只是Javascript.

试试这个:

//var merge = require('event-stream').merge; //1317 stars on GitHub
var merge = require('merge-stream');         //102 stars on GitHub
//var merge = require('merge2');             //75 stars on GitHub
//var merge = require('stream-series');      //23 stars on GitHub, keeps events in order
//var merge = require('gulp-merge');         //renamed to merge2
/*var merge = require('streamqueue')         //54 stars on GitHub
    .bind(null, {objectMode: true}); //required for streamqueue vinyl streams
*/

function firstGroup() {
  return gulp.src('some/files/*.js')
    .pipe(doSomething())
    .pipe(concat('some-scripts.js'));
}
gulp.task('firstGroup', funtion() {
  return firstGroup()
    .pipe(gulp.dest('dest'));
});

function secondGroup() {
  return gulp.src('some/other/files/*.js')
    .pipe(doSomethingElse())
    .pipe(concat('some-other-scripts.js'));
}
gulp.task('secondGroup', function() {
  return secondGroup()
    .pipe(gulp.dest('dest'));
});

gulp.task('allScripts', function() {
  return merge(firstGroup(), secondGroup())
    .pipe(concat('all-scripts.js'))
    .pipe(gulp.dest('dest'))
});
Run Code Online (Sandbox Code Playgroud)

并且可能比以上更好地命名您的任务及其相关功能.

话虽如此,删除上一个任务中的文件可能仍然更容易,更清晰.

var del = require('del');

gulp.task('allScripts', ['firstGroup','secondGroup'], function(done) {
  var intermediariesGlob = ['dest/some-scripts.js','dest/some-other-scripts.js'];
  gulp.src(intermediariesGlob)
    .pipe(concat('all-scripts.js'))
    .pipe(gulp.dest('dest'))
    .on('end', function() {
      del(intermediariesGlob)
        .then(function() {done();}); //don't just then(done), the array returned by the promise will become the error parameter of done
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案.这类似于我通常的做法,将实际处理代码分解为函数.我的构建任务只是调用`build()`,它连接,运行babel等; gzip任务调用`build().pipe(gzip()).pipe(gulp.dest('./ dist /'));`等. (2认同)