Use composeWith options in sub-generator
Asked Answered
I

1

10

I'm putting together a Yeoman Generator and having trouble understanding how the options parameter of composeWith() works. My goal is to pass user input from the main generator's prompt to sub-generators, and I thought options was the way of doing this.

My main generator's prompting looks something like this:

prompting: function () {
    var done = this.async();

    var prompts = [
      {
        type    : 'input',
        name    : 'name',
        message : 'What is the name of your project?',
        default : this.appname // Default to current folder name
      }
    ];

    this.prompt(prompts, function (answers) {

        this.composeWith('app:subgenerator', {
          options: {
            name: answers.name;
          }
        },
        {
          local: require.resolve('generator-angular/app')
        });
        done();
    }.bind(this)
  )
}

I've tried in my sub-generator to set a local variable using the arguments in the constructor (because I assumed that's where the options would be), like this:

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);
    this.foo = arguments.options.name;
  }
}

But this didn't work. I tried console logging the arguments variable, and it shows that options is an object, but it appears to be empty.

Is this how I can pass user input through a generator to another, or is there another way to do that?

Isle answered 22/4, 2015 at 20:51 Comment(0)
I
7

Your sub-generator needs to be written just as you'd write a normal ones expecting options.

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);

    this.option('name');
  },

  initializing: function () {
    console.log(this.options.name)
  }
}

See the user interaction documentation for more details.

Implead answered 23/4, 2015 at 0:9 Comment(2)
Yep, that did the trick. Didn't quite understand how options worked from the documentation. Thanks!Isle
@JoshVickerson Feel free to send a PR to clarify our documentation, that'd be welcomed!Implead

© 2022 - 2024 — McMap. All rights reserved.