【问题标题】:How to tell Gulp when a task is finished?如何在任务完成时告诉 Gulp?
【发布时间】:2015-02-04 13:41:47
【问题描述】:

我正在尝试编写一个 gulp 插件来计算流中的文件数。 I used this as a starting point:

function count() {

  var count = 0;

  function countFiles(data) {
    count++;
    // added this as per official docs:
    this.queue(data);
  }

  function endStream() {
    console.log(count + " files processed");
    // not doing this as per original post, as it "ends" the gulp chain:
    //this.emit("end");
    // so doing this instead as per official docs:
    this.queue(null);
  }

  return through(countFiles, endStream);
}


module.exports = count;

这是一个示例任务:

gulp.task("mytask", function () {
  gulp
    .src("...files...")
    .pipe(count());                // <--- here it is
    .pipe(changed("./some/path"))
    .pipe(uglify())
    .pipe(rename({ extname: ".min.js" }))
    .pipe(gulp.dest(./some/path))
    .pipe(count());                // <--- here it is again
});

它工作得很好,只是它没有按预期开始/结束:

[14:39:12] Using gulpfile c:\foo\bar\baz\gulpfile.js
[14:39:12] Starting 'mytask'...
[14:39:12] Finished 'mytask' after 9.74 ms
9 files processed
5 files processed

这意味着事物正在异步运行并在任务完成后完成。文档说您必须使用回调或返回流。它似乎正在这样做。

如何使这个函数正常运行?是因为我使用的是through 而不是through2 插件吗?

【问题讨论】:

    标签: javascript node.js gulp node-modules


    【解决方案1】:

    在您的任务中将return 放在gulp 之前。您还没有提供任何方法让 gulp 知道您的流何时结束。

    【讨论】:

    • 我对您的原始来源所做的那些更改可以吗?我对其进行了更改,以便可以多次使用该插件。我应该继续使用through 还是through2
    • 如果你在乎的话,切换到 through2,这可能并不重要。如果它们有效,那么更改就可以了!
    • 这是一个非常有用的插件。您应该考虑将其添加到您在 GitHub 上不断增长的收藏中!我经常用它来查看在管道链中更改了多少文件(有点像上面的例子,即之前与之后)。
    • @OverZealous 你能告诉我们如何在这里使用lazypipe() (stackoverflow.com/a/28774788/235415) 从 build:js 任务中提取 jshint 和 uglify 以便它们可以在正常构建中重用吗?我们面临的问题是任务中使用的局部变量。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多