Gulp Tasks with Command Line Parameters

5

Work with a simple task of Gulp , created to perform a deploy in the production environment. In a simplified way, the task is:

gulp.task('deploy-prod', function () {
    return gulp.src('dist/**')
        .pipe(sftp({
            host: '000.000.000.000',
            user: 'user',
            pass: 'pass',
            remotePath: '/var/www/html/meusite/',
            port: 22
        }))
        .pipe(gulp.dest('dist'));
});

I swipe with com

$ gulp deploy-prod

There is another environment (of homologation) that obviously has different addresses and credentials. For this, I have a task named deploy-homolog , whose logic is the same. This is just one case, among many others, where I end up having to repeat the code of my tasks because they present slightly different characteristics at the moment of development.

My question is: is there a way to parameterize the execution of these tasks via the command line? My intention was to roll

$ gulp deploy --prod

or

$ gulp deploy --homolog

and have only one task deploy , which would execute a routine based on this flag. It is possible? If so, how?

    
asked by anonymous 15.06.2016 / 15:38

1 answer

5

By default gulp does not accept parameters in this way, but you can use the yargs module to work with these arguments (there are several modules for this situation).

I will use a simple example but that can be used to solve your problem, follow the code:

gulpfile.js

var gulp = require('gulp')
    yargs = require('yargs'),
    args = yargs.argv;

gulp.task(
    'default',
    function () {
        if (args.prod) {
            console.log('Production tasks are running.');
        }
        if (args.dev) {
            console.log('Development tasks are running');
        }
    }
);

Now you can run the jobs in production with the command gulp --prod , or, the tasks in development with comando gulp --dev for example.

Editing

I'll add a second way to get the same result, but without using a new module / dependency. Here's how:

gulpfile.js

var gulp = require('gulp');

gulp.task(
  'deploy',
  function () {
    var production = process.argv.indexOf('--production') !== -1;

    if (production) {
      console.log('Running production tasks.');
    }
    if (! production) {
      console.log('Running development tasks.');
    }
  }
);

Now you can run gulp deploy --production to run production tasks, or run gulp deploy , to run development tasks.

    
17.06.2016 / 16:25