Inquirer.js核心功能解析7种问题类型深度教学【免费下载链接】Inquirer.jsA collection of common interactive command line user interfaces.项目地址: https://gitcode.com/gh_mirrors/in/Inquirer.jsInquirer.js是一个强大的Node.js命令行交互界面库为开发者提供了丰富的交互式问题类型。无论你是构建CLI工具、脚手架还是自动化脚本Inquirer.js都能让你的命令行应用拥有出色的用户体验。本文将深入解析Inquirer.js的7种核心问题类型帮助你快速掌握这个强大的命令行交互工具。 什么是Inquirer.jsInquirer.js是一个开源的Node.js库专门用于创建美观、功能丰富的命令行交互界面。它通过简单易用的API让开发者能够轻松构建复杂的命令行问答流程支持多种输入类型和验证机制。核心优势丰富的交互类型支持文本输入、选择列表、复选框、确认对话框等高度可定制完全可配置的主题和样式国际化支持内置多语言支持现代化架构基于TypeScript开发类型安全 快速开始首先通过npm安装Inquirer.jsnpm install inquirer/prompts或者使用yarnyarn add inquirer/prompts1️⃣ 文本输入Input文本输入是最基本的交互类型适用于需要用户输入任意文本的场景。Inquirer.js的输入提示支持验证、过滤和转换功能。import { input } from inquirer/prompts; const name await input({ message: 请输入您的姓名, default: 张三, validate: (value) value.length 0 || 姓名不能为空 });关键特性支持默认值预填充内置正则表达式验证实时输入转换必填项验证2️⃣ 单选列表Select单选列表允许用户从多个选项中选择一个非常适合配置选择、菜单导航等场景。import { select, Separator } from inquirer/prompts; const framework await select({ message: 选择您的前端框架, choices: [ { name: React, value: react }, { name: Vue.js, value: vue }, { name: Angular, value: angular }, new Separator(), { name: Svelte, value: svelte, disabled: true }, { name: Solid, value: solid, disabled: (即将推出) } ] });功能亮点支持选项分组使用Separator可禁用特定选项分页显示长列表循环导航支持3️⃣ 多选复选框Checkbox复选框允许多选操作适用于需要选择多个配置项的场景如依赖包选择、功能开关等。import { checkbox } from inquirer/prompts; const features await checkbox({ message: 选择要安装的功能, choices: [ { name: TypeScript支持, value: typescript, checked: true }, { name: ESLint代码检查, value: eslint }, { name: Prettier代码格式化, value: prettier }, { name: 单元测试框架, value: testing } ], required: true });便捷功能支持全选/反选快捷键可设置默认选中项必选验证自定义图标样式4️⃣ 搜索提示Search搜索提示结合了输入框和选择列表支持实时搜索和过滤非常适合从大量选项中选择的场景。import { search } from inquirer/prompts; const package await search({ message: 搜索npm包, source: async (input) { if (!input) return []; // 调用API搜索包 const response await fetch( https://registry.npmjs.org/-/v1/search?text${input}size10 ); const data await response.json(); return data.objects.map(pkg ({ name: pkg.package.name, value: pkg.package.name, description: pkg.package.description })); } });搜索提示特色实时搜索和过滤支持异步数据源自动取消旧请求智能自动补全5️⃣ 确认对话框Confirm确认对话框用于获取用户的布尔值确认通常用于危险操作前的确认。import { confirm } from inquirer/prompts; const shouldDelete await confirm({ message: 确定要删除这个文件吗, default: false }); if (shouldDelete) { console.log(文件已删除); }6️⃣ 密码输入Password密码输入专门用于敏感信息的输入输入内容会被隐藏显示。import { password } from inquirer/prompts; const secretKey await password({ message: 请输入API密钥, mask: * });安全特性输入内容隐藏可自定义掩码字符支持验证和确认7️⃣ 编辑器输入Editor编辑器输入会在用户默认编辑器中打开临时文件适合需要输入多行内容或复杂配置的场景。import { editor } from inquirer/prompts; const commitMessage await editor({ message: 编辑提交信息, default: feat: 新增功能\n\n详细描述..., postfix: .md }); 高级定制功能国际化支持Inquirer.js提供内置的多语言支持可以自动检测系统语言或手动指定import { input, select } from inquirer/i18n; // 自动检测语言 const name await input({ message: 请输入姓名 }); // 指定语言 import prompts from inquirer/i18n/fr; const choix await prompts.select({ message: Choisissez une option });主题定制所有提示类型都支持主题定制可以完全控制界面外观const customTheme { prefix: { idle: ❓, done: ✅ }, style: { answer: (text) chalk.green(text), message: (text) chalk.bold(text), error: (text) chalk.red(text) } }; const answer await input({ message: 自定义主题示例, theme: customTheme });取消和超时处理Inquirer.js支持通过AbortSignal取消提示操作import { input } from inquirer/prompts; // 5秒超时 const answer await input( { message: 请输入5秒超时 }, { signal: AbortSignal.timeout(5000) } ).catch((error) { if (error.name AbortError) { return 默认值; } throw error; }); 实际应用场景脚手架工具配置import { input, select, checkbox, confirm } from inquirer/prompts; async function createProject() { const config { name: await input({ message: 项目名称 }), framework: await select({ message: 选择框架, choices: [React, Vue, Angular] }), features: await checkbox({ message: 选择功能, choices: [TypeScript, ESLint, 测试框架, 路由] }), confirm: await confirm({ message: 确认创建项目 }) }; if (config.confirm) { // 创建项目逻辑 console.log(项目配置完成:, config); } }命令行配置向导async function setupDatabase() { const dbConfig { type: await select({ message: 数据库类型, choices: [MySQL, PostgreSQL, MongoDB, SQLite] }), host: await input({ message: 数据库主机, default: localhost }), port: await input({ message: 端口号, default: 3306, validate: (value) /^\d$/.test(value) || 请输入有效端口号 }) }; return dbConfig; } 最佳实践建议1. 错误处理try { const answer await input({ message: 请输入 }); } catch (error) { if (error.name ExitPromptError) { console.log(用户取消了操作); process.exit(0); } throw error; }2. 条件式提问const useDatabase await confirm({ message: 是否需要数据库 }); let dbConfig null; if (useDatabase) { dbConfig { type: await select({ message: 选择数据库类型, choices: [MySQL, PostgreSQL] }), // 更多配置... }; }3. 批量收集答案const answers { username: await input({ message: 用户名 }), email: await input({ message: 邮箱 }), role: await select({ message: 用户角色, choices: [管理员, 编辑, 查看者] }) }; 总结Inquirer.js为Node.js命令行应用提供了强大而灵活的交互能力。通过本文介绍的7种核心问题类型你可以构建出用户体验出色的CLI工具。无论是简单的文本输入还是复杂的搜索选择Inquirer.js都能满足你的需求。核心要点回顾文本输入基础输入验证和转换单选列表优雅的选项选择界面多选复选框批量选择功能搜索提示动态过滤和异步数据确认对话框简单的布尔值确认密码输入安全的敏感信息输入编辑器输入多行文本编辑掌握这些核心功能后你将能够创建出专业级的命令行交互体验。Inquirer.js的模块化设计让你可以按需引入所需功能保持应用体积小巧。开始使用Inquirer.js让你的命令行工具变得更加友好和强大吧【免费下载链接】Inquirer.jsA collection of common interactive command line user interfaces.项目地址: https://gitcode.com/gh_mirrors/in/Inquirer.js创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考