基础项目搭建
接入 Prompts 实现交互
用 @inquirer/prompts 实现命令行问答
Prompts 简介
在 commander 已能执行默认逻辑的基础上,接入 @inquirer/prompts,可以为 CLI 增加「提问 → 等待输入 → 根据答案继续」的交互能力。它是 Inquirer.js 的现代版,API 基于 Promise,适合与 async/await 配合使用。
主要特点:
- 多种输入类型 — 文本、选择、确认、密码等,满足常见 CLI 场景
- 统一的交互体验 — 提示样式一致,支持校验与默认值
- 类型安全 — 提供 TypeScript 类型定义
- 异步 API — 所有方法返回 Promise,需在 async 函数中用 await
- 校验与转换 — 可对用户输入做校验或格式化后再使用
常用方法一览:
input— 单行文本输入select— 单选列表checkbox— 多选列表confirm— 是/否确认password— 密码输入(输入时隐藏字符)
初始化步骤
1. 安装 prompts
在项目根目录安装。官方仓库: @inquirer/prompts
npm install @inquirer/prompts -w @repo/cg2. 导入 prompts 模块
在 src/cmd/root.ts 顶部引入 input,用于下面的「输入名字」示例。
import { Command } from 'commander'
import { input } from '@inquirer/prompts'
// ... 其他代码3. 将 action 改为异步函数
input() 等 prompts 方法返回的是 Promise,必须在 async 函数里用 await 才能拿到用户输入,因此需要把原来的 action 回调改成 async () => { ... }。
program
.name("code-gen")
.description("代码生成器 CLI 工具")
.version("1.0.0")
.action(() => {
.action(async () => {
console.log("代码生成cmd工具");
});小结: 使用 async/await 后,可以在同一段逻辑里顺序「等待用户输入」再「根据输入继续」,代码更直观。
4. 在 action 里添加用户输入
在默认执行的逻辑中调用 input(),传入提示文案;用户输入并回车后,返回值即为输入的字符串,再按需使用(例如打印)。
program.action(async () => {
console.log('代码生成cmd工具')
const answer = await input({ message: '输入你的名字' })
console.log('你的名字是:', answer)
})说明: message 即终端里看到的提示文字;await input(...) 会阻塞直到用户回车,返回值为用户输入的字符串。
5. 完整代码示例
import { Command } from 'commander'
import { input } from '@inquirer/prompts'
const program = new Command()
program
.name('code-gen')
.description('代码生成器 CLI 工具')
.version('1.0.0')
.action(async () => {
console.log('代码生成cmd工具')
const answer = await input({ message: '输入你的名字' })
console.log('你的名字是:', answer)
})
program.parse()6. 运行测试
在项目根目录执行:
bun run packages/cg/src/index.ts预期效果: 先输出「代码生成cmd工具」,然后出现提示 ? 输入你的名字 ›,输入任意名字并回车后,会再输出一行「你的名字是: [你输入的名字]」。
Git 提交
git add .
git commit -m "feat: 添加prompts交互功能"