plop

Plop.js How to create a prompt of list of choices with conditions


I have an object of templates and I want to have a prompt with this list that sends to other prompt based on condition

My object

export const myTempates = {
  endpoint: 'lambda-function-api-endpoint',
  handlerTest: 'handler-test-file',
  handlerIntegrationTest: 'handler-integration-test-file',
};

Solution

  • First of all adding multiple generators will create a list of inputs but if you want a list of inputs in a genertor you can do like this :

    To create a prompt list you can use type: 'list' with type: 'input' and use Object.values(myTempates) to get all the templates you have in myTemplates object

    To have a prompt based on condition you can use when

    plop.setGenerator('myGenerator', {
      prompts: [
        {
          type: 'list',
          name: 'template',
          message: 'Choose a template',
          choices: Object.values(myTempates),
        },
        {
          when(context) {
            return context.template.includes(myTempates.endpoint);
          },
          type: 'input',
          name: 'name',
          message: 'Choose a lambda function name',
        },
        {
          when(context) {
            return context.template.includes(myTempates.handlerTest);
          },
          type: 'input',
          name: 'name',
          message: 'Choose test file name',
        },
        {
          when(context) {
            return context.template.includes(myTempates.handlerIntegrationTest);
          },
          type: 'input',
          name: 'name',
          message: 'Choose integration test file name',
        },
      ],
      actions: [],
    });