簡體   English   中英

Yeoman generator-如何根據提示的參數更改某些文件的內容

[英]Yeoman generator - How to change the content of some file depending on a prompted param

我正在編寫一個生成器,其中將向用戶提示一個參數,我們稱其為option 根據其答案,我想更改輸出文件之一:

SomeClass.java

public class SomeClass{

    //if option=x I don't want to include this attribute:
    private String field1;

    //if option=x I want to generate an attribute with the value of the promted attribute
    private String ${info};

如何執行上述評論中所述的操作?

index.js

在這里,在prompting()方法中,您將聲明所有提示以及包含名稱的提示類型。 然后在writing() ,將它們傳遞給模板,這里是MyClass.java

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the remarkable ' + chalk.red('generator-react-starter-kit-relay-container') + ' generator!'
    ));

    const prompts = [{
      type: 'input',
      name: 'info',
      message: 'INFO IN YOUR CLASS'
    }, {
      type: 'confirm',
      name: 'x',
      message: 'YOUR OPTION X'
    }];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  }

  writing() {
    this.fs.copyTpl(
      this.templatePath('MyClass.js'),
      this.destinationPath(<YOUR DESTINATION PATH>),
      {
        info: this.props.info,
        x: this.props.x
      }
    );
  } 
};

模板/MyClass.java

public class MyClass{

    <% if (x) { %>
    private String <%= info %>;
    <% } else { %>
    private String field1;
    <% } %>

}

這是我解決的方法:

SomeClass.java:

public class SomeClass{

    <%_ if (option == 'x') { _%>
    private String field1;
    <%_ } _%>

    private String <%= nombre %>;

這是生成器代碼:

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the super-duper ' + chalk.red('generator-mygenerator') + ' generator!'
    ));

    const prompts = [{
      type: 'input',
      name: 'option',
      message: 'Option?',
      default: 'x'
    },
    {
      type: 'input',
      name: 'info',
      message: 'Field name?',
      default: 'field'
    }
    ];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  }

  writing() {
    this.fs.copyTpl(
      this.templatePath('SomeClass.java'),
      this.destinationPath('SomeClass.java'), this.props);
  }
}

暫無
暫無

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

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