如何从Node.js运行gulp任务 - gulp.start()的更好的替代方案?

时间:2016-04-15 14:02:27

标签: javascript node.js gulp

我想知道从节点应用程序运行gulp任务的正确方法是什么。

目前我正在使用以下代码,但我想知道是否:

  • 如何检测任务何时成功执行?
  • 检测任务中的任何错误?

我读到gulp.start()它真的不是一个公共API,如果它是真的,有什么选择?

require('./gulpfile.js');
gulp.start('release', function () {
  // do smt
});

2 个答案:

答案 0 :(得分:3)

gulp.start()不属于Offical Gulp API,这是真的。这是因为gulp任务不应该从其他应用程序执行,而是从命令行执行。

然而,Gulp本身从另一个名为Orchestrator

的项目中继承了其大部分任务运行能力,包括start()函数。

(当我说它'继承'他们,我字面意思意味着'inherits' .Gulp真的不比Orchestrator + Node.js Streams +更多Vinyl files +一些胶+ lots and lots of plugins。)

现在,Orchestrator本身非常应该从常规Node.js应用程序中执行。这意味着没有使用gulp.start()函数的技术理由不存在。

由于gulp.start()仅从orchestrator.start()继承,所有accompaning documentation都适用。该文档可以解答有关在任务执行期间检测到成功终止和错误的问题:

gulp.start('release', function (err) {
  if (err) {
    // an error occured
  } else {
    // success
  }
});

但有一点需要注意:,因为gulp.start()不是官方API的一部分,因此可能会发生变化。这种变化已经出现。从版本4.0开始,Gulp将不再继承Orchestrator,而是从Undertaker继承。这意味着gulp.start()将被取消gulp.series()gulp.parallel()

gulp.series('release')(function(err) {
  if (err) {
    // an error occured
  } else {
    // success
  }
});

答案 1 :(得分:0)

Gulp会自动在你的gulpfile中查找你的默认任务,并在那里运行它;你不必使用gulp.start()。

gulp.task('default', ['dependencyTask1name', ..., 'dependencyTaskXname'], function () {
  // Do stuff, produce output, what-have-you. I usually just place a console.log statement here with distinctive output, as well as inside every other task.
});

Gulp会在每个任务的开始和结束时通知终端。

[01:27:54] Starting 'default'...
[01:27:54] Finished 'default' after 51 μs

如果Gulp由于错误而无法完成任务,它也会将该错误输出到终端。示例任务:

gulp.task('routerStuff', function() {
  console.log('routes compiling.');
  return gulp.src('./source/index.js')
      .pipe(babel())s
      .pipe(gulp.dest('./routes/'));
});

终端输出:

$ gulp
/Users/EMC3/Documents/node-wordpress/gulpfile.js:35
      .pipe(babel())s
                    ^

SyntaxError: Unexpected identifier
...