2016年12月26日 星期一

[Gulp] Multiple environments - gulp-util

 gulp     gulp-util  

              
Introduction


In a project, there are always multiple environments such as,

Development
Test
Staging
Production

So how to run the different gulp tasks depends on current environment?
gulp-util is one of the most useful solution.


Use gulp-util


When there is only Development and Production environments

gulpfile.js

var gulp = require('gulp');
var util = require('gulp-util');


var config = {
    production: !!util.env.production
};

gulp.task('build', function () {
    if (config.production == true) {
        //return gulp.src(XXX).pipe(…);
    }
    else {
        //return gulp.src(XXX).pipe(…);
    }
})


PS.
util.env.production will be “true” when running the task as Production, but util.env.production will be undefined when we does’t run the task as Production environment. So we use !!util.env.production to set it as “false” in this case.


Run task

For dev (Development)

 $ gulp myTaskName  

For prod (Production)

 $ gulp myTaskName --production 



For more complicated environments

When we have more than dev/prod environments, we could use gulp-util like this way.



gulpfile.js

var gulp = require('gulp');
var util = require('gulp-util');

//Dev
function doDevTask() {
    if (util.env.env === "dev") {
        //return gulp.src(XXX).pipe(...);
    }
    else {
        return util.noop();
    }
}

//Staging
function doStgTask() {
    if (util.env.env === "stg") {
        //return gulp.src(YYY).pipe(...);
    }
    else {
        return util.noop();
    }
}

//Production
function doProdTask() {
    if (util.env.env === "prod") {
        //return gulp.src(ZZZ).pipe(...);
    }
    else {
        return util.noop();
    }
}

gulp.task('build', function () {

    doDevTask()
    doStgTask()
    doProdTask();
})

The key point is when the task doesn’t meet the current environment, it returns
util.noop() and do nothing.


(From gulp-util)




Run task

 $ gulp myTaskName --env=dev 
Or    
$ gulp myTaskName --env=stg 
Or
$ gulp myTaskName --env=prod 



Reference


沒有留言:

張貼留言