一. 使用
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" }];
效果:
寫在后面:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com