写在前面:
开始通过npm init
创建package.json
的时候就有大量与用户的交互(当然也可以通过参数来忽略输入);而现在大多数工程都是通过脚手架来创建的,使用脚手架的时候最明显的就是与命令行的交互,如果想自己做一个脚手架或者在某些时候要与用户进行交互,这个时候就不得不提到inquirer.js
了。
零. 介绍
由于交互的问题种类不同,inquirer为每个问题提供很多参数:
上面的属性(除
transformer
外)在下面都有对应使用。
一. 使用
0. 语法结构
const inquirer = require('inquirer');const promptList = [ // 具体交互内容];inquirer.prompt(promptList).then(answers => { console.log(answers); // 返回的结果})
1. input
const promptList = [{ type: 'input', message: '设置一个用户名:', name: 'name', default: "test_user" // 默认值},{ type: 'input', message: '请输入手机号:', name: 'phone', validate: function(val) { if(val.match(//d{11}/g)) { // 校验位数 return val; } return "请输入11位数字"; }}];
效果:
2. confirm
const promptList = [{ type: "confirm", message: "是否使用监听?", name: "watch", prefix: "前缀"},{ type: "confirm", message: "是否进行文件过滤?", name: "filter", suffix: "后缀", when: function(answers) { // 当watch为true的时候才会提问当前问题 return answers.watch }}];
效果:
3. list
const promptList = [{ type: 'list', message: '请选择一种水果:', name: 'fruit', choices: [ "Apple", "Pear", "Banana" ], filter: function (val) { // 使用filter将回答变为小写 return val.toLowerCase(); }}];
效果:
4. rawlist
const promptList = [{ type: 'rawlist', message: '请选择一种水果:', name: 'fruit', choices: [ "Apple", "Pear", "Banana" ]}];
效果:
5. expand
const promptList = [{ type: "expand", message: "请选择一种水果:", name: "fruit", choices: [ { key: "a", name: "Apple", value: "apple" }, { key: "O", name: "Orange", value: "orange" }, { key: "p", name: "Pear", value: "pear" } ]}];
效果:
6. checkbox
const promptList = [{ type: "checkbox", message: "选择颜色:", name: "color", choices: [ { name: "red" }, new inquirer.Separator(), // 添加分隔符 { name: "blur", checked: true // 默认选中 }, { name: "green" }, new inquirer.Separator("--- 分隔符 ---"), // 自定义分隔符 { name: "yellow" } ]}];// 或者下面这样const promptList = [{ type: "checkbox", message: "选择颜色:", name: "color", choices: [ "red", "blur", "green", "yellow" ], pageSize: 2 // 设置行数}];
效果:
7. password
const promptList = [{ type: "password", // 密码为密文输入 message: "请输入密码:", name: "pwd"}];
效果:
8. editor
const promptList = [{ type: "editor", message: "请输入备注:", name: "editor"}];
效果:
写在后面:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。
新闻热点
疑难解答