Stop Gulp Task if Conditions are met

对着背影说爱祢 提交于 2019-12-12 08:37:13

问题


I am trying to make it so if a --theme flag isn't specified it stops the gulp task and wondering the best way to do it in a DRY way.

I would like each individual task to stop if a --theme isn't specified and also have the default task stop if it isn't met.

I have tried a few things with no luck so far.

Thanks,

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

    if(typeof(args.theme) == 'undefined' || args.theme === true) {
        console.log(msg.noTheme);
        return; // end task
    }

    // run rest of task...

});

gulp.task('test-2', function() {

    if(typeof(args.theme) == 'undefined' || args.theme === true) {
        console.log(msg.noTheme);
        return; // end task
    }

    // run rest of task...

});

gulp.task('default', ['test-1', 'test-2']);

回答1:


You can simply stop the script with:

process.exit()



回答2:


I think the easiest way would be to create a verifyArgs function which throws an error when the requirements aren't met:

function verifyArgs() {
  if(typeof(args.theme) == 'undefined' || args.theme === true) {
    throw Error(msg.noTheme);
  }
}

gulp.task('test', function() {
    verifyArgs();
    // run rest of task...
});

gulp.task('test-2', function() {
    verifyArgs();
    // run rest of task...
});

gulp.task('default', ['test-1', 'test-2']);



回答3:


Some sort of async function might help you here. Maybe like this:

function processArgs(callback) {
  if(typeof(args.theme) == 'undefined' || args.theme === true) {
    return callback(new Error('Theme Not Defined'));
  }
  return callback();
}

gulp.task('test', function(done) {
  processArgs(function(err) {
    if(err) {
      console.log(err); 
      return done(err);
     }

    //else run my task
  })
});


来源:https://stackoverflow.com/questions/28485162/stop-gulp-task-if-conditions-are-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!