Gulp condition inside pipe

家住魔仙堡 提交于 2021-02-05 20:48:21

问题


How can I do a condition inside Gulp pipe to output to a different destination.

g.task('sass', function() {
  return g.src(sources.sass).pipe(changed(output.css)).pipe(sass({
    style: 'compressed',
    sourcemap: true
  })).pipe(function() {
    if (..) {
      g.dest(output.css);
    } else {
      g.dest(output.css2);
    }
  }).pipe(notify('scss converted to css and
compressed
<%=f ile.relative %>'));
});

回答1:


Use the gulp-if plugin:

var gulpif = require('gulp-if');

g.task('sass', function() {
    return g.src(sources.sass)
        .pipe(changed(output.css))
        .pipe(sass({style:'compressed', sourcemap:true}))

        // Conditional output
        .pipe(gulpif(condition1, g.dest(output.css)))
        .pipe(gulpif(condition2, g.dest(output.css2)))

        .pipe(notify('scss converted to css and compressed <%= file.relative %>'));
});



回答2:


The solution without any new dependencies:

The gulp.src function returns a stream, so you can use it ;)
Look at the gulp docs.

gulp.task('task', function () {
  let stream = gulp.src(sources.sass)
    .pipe(changed(output.css)).pipe(sass({
      style: 'compressed',
      sourcemap: true
    }));

  if (2 + 2 === 4) {
    stream = stream
      .pipe(someModule())
      .pipe(someModule2());
  }

  else {
    stream = stream
      .pipe(someModule3())
      .pipe(someModule4());
  }

  stream = stream.pipe(notify('scss converted to css and compressed'));

  return stream;
});



回答3:


I suggest you to use expression something like this:

g.task('sass', function(){
  var destinationFileName;

  if (...) {
    destinationFileName = 'output.css';
  } else {
    destinationFileName = 'output2.css';
  }

  return g.src(sources.sass)
    .pipe(changed(output.css))
    .pipe(sass({style:'compressed', sourcemap:true}))
    .pipe(g.dest(destinationFileName))
    .pipe(notify('scss converted to css and compressed <%= file.relative %>'));
});



回答4:


If you do not want to add any extra dependency, you can trust good old Elvis (?:):

g.task('sass', function() {
  return g.src(sources.sass)
    .pipe(changed(output.css))
    .pipe(sass({style:'compressed', sourcemap:true}))

    // Conditional output
    .pipe(condition ? g.dest(output.css) : g.dest(output.css2))

    .pipe(notify('scss converted to css and compressed <%= file.relative %>'));
});

Or for multiple cases:

.pipe(condition1 ? g.dest(output.css) : gulp.util.noop())
.pipe(condition2 ? g.dest(output2.css) : gulp.util.noop())


来源:https://stackoverflow.com/questions/27181719/gulp-condition-inside-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!