【问题标题】:How can I run three tasks with parameters in sequence?如何按顺序运行三个带参数的任务?
【发布时间】:2016-08-08 07:37:58
【问题描述】:

到目前为止我有这个代码:

gulp.task('make_prod_aa', function () {
    makeAppHtml(config.srcAalHtml, function () {
        runSequence(
          'makeTemplate',
          'make_css_bundle',
          'rename_css_bundle',
          'make_js_bundle',
          'rename_js_bundle',
          function () {
              makeAppIndex('index-aa.html');
          });
    });
});

它允许我将参数传递给两个函数并按顺序运行函数和任务。现在我想将参数传递给第三个任务。我希望能够将config.aaTemplates 参数传递给这里的任务makeTemplate:

gulp.task('makeTemplate', function () {
    return gulp.src(config.aaTemplates)
          .pipe(print(function (file) {
              return "Added file " + file + " to template";
          }))
       .pipe(minifyHTML({ collapseWhitespace: true }))
       .pipe(templateCache({ standalone: true, root: '/app' }))
       .pipe(gulp.dest(config.destPartials))
       .pipe(gzip(gzip_options))
       .pipe(gulp.dest(config.destPartials));
});

如果有任何关于我如何做到这一点的建议,我将不胜感激。

【问题讨论】:

  • 只需将我在this answer 中向您描述的完全相同的重构应用到您的makeTemplate 任务。当然,如果你对runSequence() 中的每个任务都这样做,你最终会得到很多嵌套回调,也就是callback hell。那时最好查看async.waterfall()之类的内容。

标签: javascript node.js gulp


【解决方案1】:

我认为除了使用 JS 闭包来让所有按顺序运行的任务共享相同的配置之外,没有其他选择。 Proof

例如:

var config = require('path/to/config');

function makAppAppHtml () {
        runSequence(
          'makeTemplate',
          'make_css_bundle',
          'rename_css_bundle',
          'make_js_bundle',
          'rename_js_bundle',
          function () {
              makeAppIndex('index-aa.html');
          });
}

function makeTemplate () {
    return gulp.src(config.aaTemplates)
            .pipe(print(function (file) {
                return "Added file " + file + " to template";
            }))
         .pipe(minifyHTML({ collapseWhitespace: true }))
         .pipe(templateCache({ standalone: true, root: '/app' }))
         .pipe(gulp.dest(config.destPartials))
         .pipe(gzip(gzip_options))
         .pipe(gulp.dest(config.destPartials));
  });
}

gulp.task('make_prod_aa', makAppAppHtml);
gulp.task('makeTemplate', makeTemplate);

makeAppHtmlmakeTemplate 都可以访问配置对象,因为它是在外部范围中定义的,同样的技巧可以应用于函数范围,对于更详细的示例,我推荐 JavaScript Garden article

【讨论】:

  • 你能解释一下 JS 闭包吗?我听到人们谈论 Closure 但对此一无所知。如果你能举个例子那就太好了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2015-02-15
  • 2011-05-27
  • 1970-01-01
相关资源
最近更新 更多