You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plop.js:如何创建带条件分支的选择列表提示

基于模板对象创建交互式选择列表并实现条件跳转

方案说明

使用inquirer(Node.js生态常用的交互式命令行工具)可以快速实现需求:先展示基于模板对象生成的选择列表,再根据用户选择触发对应的后续提示。

步骤1:安装依赖

如果是CommonJS项目,安装v8版本兼容性更好:

npm install inquirer@8

如果是ESM项目,可安装最新版:

npm install inquirer

步骤2:实现代码

// CommonJS 导入方式
const inquirer = require('inquirer');
const { myTempates } = require('./path-to-your-template-file.js');

// ESM 导入方式(如果项目用ESM)
// import inquirer from 'inquirer';
// import { myTempates } from './path-to-your-template-file.js';

// 从模板对象生成选择项,同时展示对应模板值
const templateChoices = Object.keys(myTempates).map(key => ({
  name: `${key} - 模板参考: ${myTempates[key]}`,
  value: key
}));

async function startInteractivePrompt() {
  // 第一个选择列表提示
  const { selectedTemplate } = await inquirer.prompt([
    {
      type: 'list',
      name: 'selectedTemplate',
      message: '请选择要操作的模板类型:',
      choices: templateChoices
    }
  ]);

  // 根据选择结果跳转对应提示
  switch(selectedTemplate) {
    case 'endpoint':
      const { customEndpoint } = await inquirer.prompt([
        {
          type: 'input',
          name: 'customEndpoint',
          message: `请输入Lambda函数API的具体端点(模板示例: ${myTempates.endpoint}):`
        }
      ]);
      console.log(`已确认API端点配置: ${customEndpoint}`);
      // 这里可添加后续逻辑,如写入配置文件、生成代码等
      break;

    case 'handlerTest':
      const { testFile } = await inquirer.prompt([
        {
          type: 'input',
          name: 'testFile',
          message: `请输入Handler测试文件的路径/名称(模板示例: ${myTempates.handlerTest}):`
        }
      ]);
      console.log(`已指定测试文件: ${testFile}`);
      break;

    case 'handlerIntegrationTest':
      const { integrationTestFile } = await inquirer.prompt([
        {
          type: 'input',
          name: 'integrationTestFile',
          message: `请输入Handler集成测试文件的路径/名称(模板示例: ${myTempates.handlerIntegrationTest}):`
        }
      ]);
      console.log(`已指定集成测试文件: ${integrationTestFile}`);
      break;
  }
}

// 启动交互式流程
startInteractivePrompt();

关键逻辑解析

  • 用Object.keys(myTempates)提取模板对象的键,生成选择列表选项,同时展示模板值帮助用户理解
  • 通过inquirer.prompt创建list类型的选择交互
  • 使用switch语句根据用户选择的模板key,触发对应的输入提示
  • 每个分支的后续提示可根据实际需求调整类型(如input、confirm、list等)和逻辑

内容的提问来源于stack exchange,提问作者TheSmartMonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:33:00