Skip to content

inquirer 教程

一个常见的交互式命令行用户界面的集合。

inquirer.js 致力于为 node.js 提供一个易于嵌入且美观的命令行界面。

inquirer.js 能轻松处理:

  • 提供错误回调
  • 询问问题
  • 解析输入
  • 验证问题
  • 管理多步提示

下载

使用之前请先下载好依赖。

shell
npm install --save inquirer

注意模块引入方式:

inquirer@9 使用 esm 模块导入,不支持 commonjs。如需使用 require 导入,请使用 8 版本。

js
npm install --save inquirer@^8.0.0

然后使用:

js
import inquirer from 'inquirer';

inquirer
  .prompt([
    /* Pass your questions in here */
  ])
  .then((answers) => {
    // Use user feedback for... whatever!!
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });

使用

js
import inquirer from 'inquirer'

async function main() {
  const res = await inquirer.prompt([
    // 单选 string
    {
      type: 'list',
      name: 'framework',
      prefix: '<===',
      suffix: '===>',
      message: '你最喜欢的框架',
      choices: ['vue', 'react', 'angular']
    },
    // 多选 string[]
    {
      type: 'checkbox',
      name: 'food',
      prefix: '<===',
      suffix: '===>',
      message: '你喜欢的菜',
      choices: ['红烧茄子', '方便面', '水果罐头']
    },
    // 输入 string
    {
      type: 'input',
      name: 'love',
      message: '你最喜欢的人'
    },
    // 布尔值 boolean
    {
      type: 'confirm',
      name: 'isLikeRead',
      message: '喜欢读书吗?'
    },
    // 根据前面已回答的问题,判断是否提问
    {
      type: 'input',
      name: 'likeBooks',
      message: '喜欢读哪本书?',
      when(res) {
        return res.isLikeRead
      }
    } 
  ])
  return res
}


const res = await main()
console.log('最终结果:', res)

Released under the MIT License.