简体   繁体   中英

Can I define an option in a Yeoman subgenerator, and then reference that option from the base generator?

I have an EJS template file that is located in the base generator, but needs to be able to read options from both the base generator and the subgenerator.

Base Generator

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

    this.option('option1');
  },

  initializing: function() {
    this.composeWith('base:sub-gen', this.options, {
      local: require.resolve('../sub-gen'),
      link: 'strong'
      });
  }
});

Subgenerator

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

    this.option('option2');
  },
});

Template

Base generator option: <%=this.options.option1 %>
Sub-generator option: <%=this.options.option2 %>

Is there any way to reference the sub-generator options from my ejs template? Barring that, how else can I make sure that my base generator and my sub-generator all have access to the same list of options? Maybe it's possible using .yo-rc.json ?

After working on it some more, I found a solution:

  1. In both generators, set the configs in the configuring step, but read them in the default step.
  2. After reading the configs with this.config.get('key') or this.config.getAll() , save them as a property of the generator you want to use them in: this.imports = this.config.get('option-name') .

Example:

Base Generator

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

    this.option('option1');
  },

  initializing: function() {
    this.composeWith('base:sub-gen', this.options, {
      local: require.resolve('../sub-gen'),
      link: 'strong'
      });
  },

  configuring: function () {
    let configs = {
      option1: option1
    };

    this.config.set(configs);
  },

    default: function() {
        let config = this.config.getAll()
        this.imports = this.config.get('subGenOptions');
    },
});

Subgenerator

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

    this.option('option2');
  },
  configuring: function() {
    let configs = {
        subGenOptions: {
            option2: this.options.option2
        }
    }

    this.config.set(configs)
  },
});

Template (in base generator)

Base generator option: <%=options.option1 %>
Sub-generator option: <%=imports.option2 %>

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