How can a yeoman sub-generator access variables defined on the main generator?

I am doing a sub-generator and I want to pass to this sub-generator variables defined on the main generator: Some thing like that :

  writing: function() {
    console.log(this.appversion);
    var email = this.email; // Variable defined on the main controller.
    this.fs.copy(
      this.templatePath('somefile.js'),
      this.destinationPath('somefile.js')
    );

I've tried to do something like the code below on the main generator:

this.composeWith('jstack1:controller', {options: {name: 'some-name'}});

and the code below on the sub-generator

this.option('name', {/* settings */});

But I am not sure if it is a good way to do this ,furthermore I always get the following error message:

Error: Did not provide required argument [1mname[22m! at null. (C:\Users\Alexandre_\generator-jstack1\generator-generator-jstack1\node_modules\yeoman-generator\lib\base.js:359:33) at Array.forEach (native) at Base.checkRequiredArgs (C:\Users\Alexandre_\generator-jstack1\generator-generator-jstack1\node_modules\yeoman-generator\lib\base.js:355:19) at argument (C:\Users\Alexandre_\generator-jstack1\generator-generator-jstack1\node_modules\yeoman-generator\lib\base.js:321:8) at module.exports.yeoman.generators.Base.extend.initializing (C:\Users\Alexandre_\generator-jstack1\generator-generator-jstack1\generators\controller\index.js:6:10) at C:\Users\Alexandre_\generator-jstack1\generator-generator-jstack1\node_modules\yeoman-generator\lib\base.js:421:16 at processImmediate [as _immediateCallback] (timers.js:383:17)

Upvotes: 1

Views: 765

Answers (2)

I have found a way to do that, and it is very simple.

First at the main generator I add the context variables at the storage:

  var templateContext = {

    appname: this.appname,

    appdescription: this.appdescription,

    appversion: this.appversion,

    applicense: this.applicense,

    appautor: this.appautor,

    appemail: this.appemail

  };



  this.config.set('templateContext',templateContext);

then at the sub-generator I get the templateContext with:

var templateContext = this.config.get('templateContext');

Upvotes: 1

Simon Boudrias
Simon Boudrias

Reputation: 44669

But I am not sure if it is a good way to do this

Yes, this is the correct way to do it. The only way generators communicate with each other is via options and arguments. (There's also some communication possible through cache/configurations and the file system, but these are not frequent channels.)

About the error, my guess is you're extending generators.NamedBase rather than generators.Base.

Upvotes: 1

Related Questions