问题
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