Gulp tasks with command line parameters

Asked

Viewed 355 times

5

I work with a simple task of Gulp, created to realize a deploy in a 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'));
});

that I spin with the with

$ gulp deploy-prod

There is another environment (of homologation) that obviously has different address and credentials. For this, I have a task calling for 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 by presenting slightly different characteristics at times of development.

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

$ gulp deploy --prod

or

$ gulp deploy --homolog

and have only one task deploy, that would perform a routine based on this flag. Is that possible? If so, how?

1 answer

5


By default Gulp does not accept parameters this way, but you can use the module yargs 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 perform the tasks in production with the command gulp --prod, or, the tasks under development with the comando gulp --dev for example.

Editing

I will add a second way to get the same result, but without using a new module/dependency. See how it looks:

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 the gulp deploy --production to run the production tasks, or to perform the gulp deploy, to run the development tasks.

  • Good answer! The use of another module does not please me much, but it solves the problem. Let’s see if anyone else appears with a different answer. For the time being, +1

  • I understand your implication with the use of various modules/dependencies, I added a second example to my previous answer, I hope to have helped, hugs.

  • Perfect, there you go.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.