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

gkn4icbw  于 2022-12-08  发布在  Gulp
关注(0)|答案(2)|浏览(155)

我有三个gulp任务,其中最后一个任务(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
});
xdyibdwo

xdyibdwo1#

如果每件事都可以是一个单一的任务,你可以使用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'));
});

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

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

多任务解决方案:

如果你的任务结构是这样的,你不能用上面的方法把它们合并成一个任务,这是你最好的选择。从某种意义上说,它有点笨拙,因为它依赖于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;
    });
}
fdbelqdn

fdbelqdn2#

@传销有正确的想法与组合流。
但是不要忘记Gulp只是Javascript
试试这个:

const merge = require('merge-stream');
// or pick an alternative stream-merge library: 
//const merge = require('event-stream').merge; //1317 stars on GitHub
//const merge = require('merge-stream');       //102 stars on GitHub
//const merge = require('merge2');             //75 stars on GitHub
//const merge = require('stream-series');      //23 stars on GitHub, keeps events in order
//const merge = require('gulp-merge');         //renamed to merge2
/*const 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'))
});

可能你的任务和它们的相关函数的名称比上面的好一点。
也就是说,在最后一个任务中删除文件可能更容易、更清楚。

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
    });
});

相关问题