inquirer
TIP
是一款终端调查问卷得一款npm
插件。
安装
WARNING
Inquirer v9 and higher are native esm modules, this mean you cannot use the commonjs syntax require('inquirer') anymore. If you want to learn more about using native esm in Node, I'd recommend reading the following guide. Alternatively, you can rely on an older version until you're ready to upgrade your environment:(Inquirer v9和更高版本是原生esm模块,这意味着你不能再使用commonjs语法require(' Inquirer ')了。如果您想了解更多关于在Node中使用原生esm的知识,我建议您阅读下面的指南。或者,你可以依赖一个旧版本,直到你准备好升级你的环境:)
bash
npm install inquirer@^8.0.0 --save
or
yarn add inquirer@^8.0.0 --save
写个小例子看下效果
TIP
node index.js
运行下面js程序
js
// index.js
const inquirer = require('inquirer');
inquirer.prompt([
{
type: 'input',
name: 'input',
message: '你的姓名',
default: 'sanyuan',
},
{
type: 'password',
name: 'password',
message: '请输入密码',
default: 'sanyuan',
},
{
type: 'confirm',
name: 'confirm',
message: 'Are you handsome?',
default: true,
},
{
type: 'list',
name: 'list',
message: 'list',
choices: [1, 2, 3],
default: 0, // 索引
},
{
type: 'rawlist',
name: 'rawlist',
message: 'rawlist',
choices: [1, 2, 3],
default: 0,
},
{
type: 'expand',
message: 'Conflict on `file.js`: ',
name: 'overwrite',
choices: [
{
key: 'y',
name: 'Overwrite',
value: 'overwrite',
},
{
key: 'a',
name: 'Overwrite this one and all next',
value: 'overwrite_all',
},
{
key: 'd',
name: 'Show diff',
value: 'diff',
},
],
},
{
type: 'checkbox', // 多选 空格选中、i 反选、a全选
message: 'Select toppings',
name: 'toppings',
default: 'Pepperoni',
choices: [
{
name: 'Pepperoni',
checked: true,
},
{
name: 'Ham',
},
{
name: 'Ground Meat',
},
{
name: 'Bacon',
},
],
},
]).then((answers) => {
console.log('结果为:');
console.log(answers);
});
相关问题使用属性
ts
/**
* list: 问题对象中必须有type,name,message,choices等属性,同时,default选项必须为默认值在choices数组中的位置索引(Boolean); [1,2,3]
* rawlist: 与List类型类似,不同在于,list打印出来为无序列表,而rawlist打印为有序列表; [1,2,3]
* expand: 同样是生成列表,但是在choices属性中需要增加一个属性:key,这个属性用于快速选择问题的答案。类似于alias或者shorthand的东西。同时这个属性值必须为一个小写字母[{key: a, value: 1}, {key: b, value: 2}]
* checkbox: 其余诸项与list类似,主要区别在于,是以一个checkbox的形式进行选择。同时在choices数组中,带有checked: true属性的选项为默认值。
* confirm: 提问,回答为Y/N。若有default属性,则属性值应为Boolean类型;
* input: 输入得问题值
* password: 密文输入得文本值
*/
type PromptType = 'list' | 'rawlist' | 'expand' | 'checkbox' | 'confirm' | 'input' | 'password' | 'editor';
interface PromptProps{
type: PromptType; // 表示提问的类型
name: string; // 在最后获取到的answers回答对象中,作为当前这个问题的key
message: string; // 打印出来的问题标题
default: any; // 默认值
choices: Array<any>; // 选择集合
validate(): boolean; // 检验
filter(): Array<any>; // 过滤
when: Function | Boolean; // 接受当前用户输入的answers对象,并且通过返回true或者false来决定是否当前的问题应该去问。也可以是简单类型的值。
pageSize: number; // 改变渲染list,rawlist,expand或者checkbox时的行数的长度。
}