2
votes

I have two gulp tasks I need to run, one for js, one for css. I need them to run differently for build-dev (not minified) and build-prod (minified).

To do this, I stripped out the minification and gulp.dest portions of the tasks for js and css and am instead returning gulp.src to the tasks build-prod or build-dev. These two tasks build-prod or build-dev are now responsible for manipulating the js and css tasks differently.

How can I return the tasks' gulp.src to build-prod or build-dev for continued piping?

Note: since it's a stream, it seems I'm returning the stream after the last pipe finishes for that task, then since it's asynchronous, why can't I chain pipes after gulp.src returns?

gulp.task('css', function() {
    return gulp.src('css/**.css')
        .pipe(autoprefixer('last 10 version'))
        .pipe(concatCss('main.css'));
        // .pipe(minifycss())
        // .pipe(gulp.dest('build/css'));
});

gulp.task('js', ...
    return gulp.src(['./js/**/*.js'])
       .pipe(
           ... // Huge function that I don't want to duplicate
});

gulp.task('build-prod', function() {
    gulp.run('css')
        .pipe(minifycss())
        .pipe(gulp.dest('build/css'));

    gulp.run('scripts')
        .pipe(minifyjs())
        .pipe(gulp.dest('build/js'));
});

gulp.task('build-dev', function() {
    gulp.run('css')
        .pipe(gulp.dest('build/css'));

    gulp.run('scripts')
        .pipe(gulp.dest('build/js'));
});
2

2 Answers

0
votes

Why not make a function you call in multiple places?

function cssTask() {
  return gulp.src('css/**.css')
    .pipe(autoprefixer('last 10 version'))
    .pipe(concatCss('main.css'));
}

gulp.task('css', function () {
  return cssTask();
});

gulp.task('build-prod', function () {
  cssTask()
    .pipe(minifycss())
    .pipe(gulp.dest('build/css'));
});

gulp.task('build-dev', function () {
  cssTask()
    .pipe(gulp.dest('build/css'));
});
0
votes

The best way is to use gulp conditionals: .pipe(gulpif(isProduction, minifycss()))

Gulp If is a great way to do it.

let isProduction = false;
...
gulp.task('css', function() {
    return gulp.src('css/**.css')
        .pipe(autoprefixer('last 10 version'))
        .pipe(concatCss('main.css'))
        .pipe(gulpif(isProduction, minifycss())) // conditional
        .pipe(gulp.dest('build/css'));
});

gulp.task('build-prod', function() {
    isProduction = true;
    gulp.run('css');
});

gulp.task('build-dev', function() {
    isProduction = false;
    gulp.run('css');
});