简体   繁体   中英

Run only a single function in a Yeoman generator

How can I run only a single function in a generator (and end the generator) if a flag is set? What is the preferred way to achieve this?

var MyGenerator = yeoman.generators.Base.extend({

  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

    this.option('flag', {
      desc: 'Do something',
      type: String,
      required: false,
      defaults: null
    });
  },

  runOnlyThisIfFlagIsSet: function() {
    if(this.options.flag) {
      // do stuff and end the generator so that it does all the things defined here
    }   
  },

  doNotRunThis: function() {
    // I don't want this to run if the flag is set
  },

  iCouldDoThisButItIsTooRepetitive: function() {
    if(!this.options.flag) {
      // do stuff
    } 
  }
});

module.exports = MyGenerator;

yo myGeneratorName --flag

Maybe you're over thinking this? Based on http://yeoman.io/authoring/running-context.html , I would recommend only having maybe one function in your generator anyway (default?). Read the section called "Helper and private methods" if you want to break your generator into additional methods.

var MyGenerator = yeoman.generators.Base.extend({

  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

    this.option('flag', {
      desc: 'Do something',
      type: String,
      required: false,
      defaults: null
    });
  },

  default: function() {
    if(this.options.flag) {
      // do stuff and end the generator so that it does all the things defined here. Use the documentation link above to figure out how to create private methods you can call from here. 
    }    
  }


});

module.exports = MyGenerator;

If the flag is not set, the generator will just exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM