← 中文资源

简体中文版本

Inquirer 复选多选交互流程

用 Inquirer 的 checkbox、input 与 confirm 组合出多步交互流程:默认勾选、禁用选项、格式校验与答案驱动分支。

阅读英文原文

示例说明

纯参数式 CLI 对新用户不友好,交互式补全能引导出合法输入。checkbox 提供多选并支持默认勾选与禁用项说明;input 配合 validate 正则把格式错误拦在提交前;confirm 用于不可逆操作的前置确认。answers 对象集中收集全部回答,便于后续分支。

技术要点

  • checkbox 的 checked 字段设置默认勾选
  • disabled 选项附带不可选原因
  • validate 返回字符串即显示错误并重新询问

代码解读

services 问题列出三个服务,api-gateway 默认选中,search 因数据源下线被禁用并显示原因;validate 要求至少选一项。ticket 的校验用正则匹配 OPS 加四到六位数字,失败时返回错误提示字符串而非抛异常,Inquirer 会原地重新提问。

使用建议

交互式流程要给 CI 留出非交互参数通道,两者可并存。敏感输入应换 type 为 password 避免回显。选项数量很多时启用分页而非一屏塞满。

代码示例

import inquirer from 'inquirer';

const answers = await inquirer.prompt([
  {
    type: 'checkbox',
    name: 'services',
    message: 'Which services should the report cover?',
    choices: [
      { name: 'api-gateway', value: 'gw', checked: true },
      { name: 'billing', value: 'bill' },
      { name: 'search', value: 'search', disabled: 'data source offline' },
    ],
    validate: (list) => (list.length > 0 ? true : 'select at least one service'),
  },
  {
    type: 'input',
    name: 'ticket',
    message: 'Ops ticket number:',
    validate: (value) =>
      /^OPS-\d{4,6}$/.test(value) ? true : 'expected format: OPS-12345',
  },
  {
    type: 'confirm',
    name: 'notify',
    message: 'send summary to the on-call channel?',
    default: false,
  },
]);

console.log('report scope:', answers.services, 'ticket:', answers.ticket);