Yannick Pereira-Reis bio photo

Yannick Pereira-Reis

DevOps (docker swarm, haproxy, CI/CD, ELK, prometheus, grafana, ansible, automation, RabbitMQ, LVM, MySQL replication...) and fullstack web developer Symfony 2/3/4/5 + VueJs in Valence (France).

Twitter LinkedIn Github

As describe on the Gulp website, this tool allows you to automate and enhance your workflow and is Easy to Learn, Easy to use, Efficient and High Quality… I totally agree with this. But I’ve been stuck by a small problem in the past few days : how to get an environment variable to build conditional tasks ?

Gulp

Gulp util install

First of all you need to add a new node dependency called gulp-util in your packages.json file:

"devDependencies": {
    "gulp-util": "x.y.z"
},

Install it with your favorite command:

npm install

Use gulp util in your Gulpfile.js

  • Require:
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
...
var gutil = require('gulp-util');
  • Tasks:
gulp.task('stylesheet', function() {
    return gulp.src([])
    .pipe(sass())
    .pipe(concat('styles.css'))
    .pipe(gutil.env.env === 'prod' ? minifyCss() : gutil.noop())
    .pipe(gulp.dest('web/css'));
});
  • DRY

It’s possible that you have many gulp tasks that need this behavior:

function minifyIfNeeded() {
    return gutil.env.env === 'prod'
        ? minify()
        : gutil.noop();
}

gulp.task('stylesheet', function() {
    return gulp.src([])
    .pipe(sass())
    .pipe(concat('styles.css'))
    .pipe(minifyIfNeeded())
    .pipe(gulp.dest('web/css'));
});

Give gulp configuration through the command line

gulp stylesheet
gulp --env=prod stylesheet
gulp --env=dev stylesheet
gulp --env=$(ENVIRONMENT_VAR) stylesheet

you could change the --env option with anything else:

gulp --type=prod stylesheet

and use this in your Gulpfile.js:

gulp.task('stylesheet', function() {
    return gulp.src([])
    .pipe(sass())
    .pipe(concat('styles.css'))
    .pipe(gutil.env.type === 'prod' ? minifyCss() : gutil.noop())
    .pipe(gulp.dest('web/css'));
});

More resources