【问题标题】:Combining GulpJS Tasks结合 GulpJS 任务
【发布时间】:2014-07-12 22:40:45
【问题描述】:

所以我有以下所有与安装和复制 bower 文件相关的 GulpJS 任务:

gulp.task('bower-install', function() {
  var command = 'bower install';
  gutil.log(gutil.colors.cyan('running command:'), command);

  return gulp.src('', {read: false})
  .pipe(shell([
    command
  ]));
});

gulp.task('bower-copy', function() {
  return gulp.src(gulpConfig.bowerCopy.map(function(item) {
    return './bower_components/' + item;
  }), {base: './bower_components'})
  .pipe(gulp.dest('./htdocs/components'));
});

gulp.task('bower-copy-clean', function() {
  return gulp.src('./bower_components')
  .pipe(clean());
});

gulp.task('bower-clean', function() {
  return gulp.src('./htdocs/components')
  .pipe(clean());
});

gulp.task('bower', 'Download and move bower packages', function(done) {
  runSequence(
    'bower-install',
    'bower-clean',
    'bower-copy',
    'bower-copy-clean',
    done
  );
});

我这样做是因为我需要这些任务一个接一个地依次运行。虽然当我运行 gulp bower 时一切都按预期工作,但我想构造这段代码,以便唯一暴露的任务是 bower,因为所有 bower-* 自己运行毫无意义。

有没有办法编写这段代码,让所有bower-* 任务一个接一个地运行,但只公开bower 任务?

【问题讨论】:

    标签: build gulp


    【解决方案1】:

    因为 gulpfile 只是一个普通的节点应用程序,通常当我们遇到这样的卡顿情况时,最好问一下“如果我们没有 gulp,我们会怎么做?”这是我的解决方案:

    var async = require('async');
    var del = require('del');
    var spawn = require('child_process').spawn;
    
    function bowerInstall(cb) {
      var command = 'bower install';
      gutil.log(gutil.colors.cyan('running command:'), command);
      var childProcess = spawn('bower', ['install'], {
        cwd: process.cwd(),
        stdio: 'inherit'
      }).on('close', cb);
    });
    
    function bowerCopy(cb) {
      gulp.src(gulpConfig.bowerCopy.map(function(item) {
        return './bower_components/' + item;
      }), {base: './bower_components'})
      .pipe(gulp.dest('./htdocs/components'))
      .on('end', cb);
    });
    
    function bowerCopyClean(cb) {
      del('./bower_components', cb);
    });
    
    function bowerClean() {
      del('./htdocs/components', cb);
    });
    
    gulp.task('bower', 'Download and move bower packages', function(done) {
      async.series([
        bowerInstall,
        bowerClean,
        bowerCopy,
        bowerCopyClean
      ], done);
    });
    

    请注意,我还没有将整个 bower_components 和 htdocs/components 目录读入 ram,从而大大加快了您的构建速度。

    【讨论】:

    • 这工作正常,但是当我使用 gulp-shell 时,它会将命令的输出输出到屏幕上,这可以通过 exec 实现吗?
    • 是的,exec的回调实际上是function (err, stdout, stderr) {,所以你只需console.log(stdout)console.log(stderr)
    • 我实际上更新了您的代码以使用spawn 而不是exec。使用spawn 而不是exec 允许它在使用exec 的回调时将子进程的输出进行蒸汽处理,一旦完成就将其吐出,这并不理想。您提到的所有其他内容正是我想要的,谢谢。
    猜你喜欢
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多