· Updated

How to get environment variables in a gulpfile

  • development

This article was written in 2015. Tools and versions have moved on since then, so some content may be outdated.

As described 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

← All posts