Search code examples
javascriptnode.jsyeomanyeoman-generator

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


I am writing a generator in which a user will be prompted a param, let's call it option. Depending on its answer I want to change one of the output files:

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

How can I do the actions described in the comments above?


Solution

  • index.js

    Here in the prompting() method you will declared all your prompts and the type of prompt with names included. Then in writing() you will pass those to the template which here is 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
          }
        );
      } 
    };
    

    templates/MyClass.java

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