簡體   English   中英

我可以在Yeoman子生成器中定義一個選項,然后從基本生成器中引用該選項嗎?

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

我有一個EJS模板文件,該文件位於基本生成器中,但需要能夠從基本生成器和子生成器中讀取選項。

基礎發電機

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'
      });
  }
});

子發電機

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

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

模板

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

有什么方法可以從我的ejs模板中引用子生成器選項嗎? 除非如此,否則我如何才能確保我的基本生成器和子生成器都可以訪問相同的選項列表? 也許可以使用.yo-rc.json嗎?

經過更多努力之后,我找到了解決方案:

  1. 在兩個生成器中,都在configuring步驟中設置configuring ,但在default步驟中讀取它們。
  2. 使用this.config.get('key')this.config.getAll()閱讀配置后,將它們另存為要在其中使用它們的生成器的屬性: this.imports = this.config.get('option-name')

例:

基礎發電機

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');
    },
});

子發電機

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)
  },
});

模板(在基本生成器中)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM