在 gulp 中合并多个 src 流?

Combining multiple src streams in gulp?

我想知道是否有任何方法可以将这两个单独的任务合并为一个。

concat-js 任务要求生成的文件在 运行 之前存在。任务 cache-angular-templates 生成该文件。生成的文件需要包含在 concat 输出中。 concat-js 完成后,可以删除该文件——不再需要它了。

似乎我应该能够以某种方式将 cache-angular-tempaltes 中使用的流传输到 concat-js 使用的流中。

gulp.task('concat-js', ['cache-angular-templates'], function () {
    var concatOutputPath = path.dirname(paths.compiledScriptsFile),
        concatOutputFileName = path.basename(paths.compiledScriptsFile),
        jsFiles = [].concat(
            paths.libScripts,
            paths.appScripts,
            paths.templateScriptFile,
            notpath(paths.compiledScriptsFile),
            notpath(paths.specMockScripts),
            notpath(paths.specScripts)
        );

    return gulp
        .src(jsFiles)
        .pipe(buildTools.concat(concatOutputFileName))
        .pipe(gulp.dest(concatOutputPath))
        .on('end', function () {
            del(paths.templateScriptFile);
        })
    ;
});

gulp.task('cache-angular-templates', function () {
    var cacheOutputPath = path.dirname(paths.templateScriptFile),
        cacheOutputFileName = path.basename(paths.templateScriptFile);

    var options = {
        root: '/' + cacheOutputPath,
        standalone: true,
        filename: cacheOutputFileName
    };

    return gulp
        .src(paths.templates)
        .pipe(buildTools.angularTemplatecache(options))
        .pipe(gulp.dest(cacheOutputPath))
    ;
});

确实应该合并它们,因为 Gulp 的想法之一是消除中间临时文件。

实现它的方法之一是:

  1. cache-angular-templates 转换为 returns 模板流的函数,我们称之为 getTemplateStream;
  2. 从中删除 .pipe(gulp.dest(cacheOutputPath))
  3. 使用 event-stream 合并流,然后再将其连接到主任务上。你的主要任务会变成这样:
var es = require('event-stream');

gulp.task('concat-js', function () {
    var concatOutputPath = path.dirname(paths.compiledScriptsFile),
        concatOutputFileName = path.basename(paths.compiledScriptsFile),
        jsFiles = [].concat(
            paths.libScripts,
            paths.appScripts,
            notpath(paths.compiledScriptsFile),
            notpath(paths.specMockScripts),
            notpath(paths.specScripts)
        );

    return es.merge(gulp.src(jsFiles), getTemplateStream())
        .pipe(buildTools.concat(concatOutputFileName))
        .pipe(gulp.dest(concatOutputPath));
});

function getTemplateStream() {
    var options = {
        root: '/' + cacheOutputPath,
        standalone: true,
        filename: cacheOutputFileName
    };

    return gulp
        .src(paths.templates)
        .pipe(buildTools.angularTemplatecache(options));
}

通过这样做,您合并了两个流,并且您的 getTemplateStream 的输出文件将被发送到管道。