Skip to content

inquirer-命令行交互

javascript
import inquirer from "inquirer";
import { existsSync } from "fs";
import { rm } from "fs/promises";
import path from "path";
javascript
/* 
  type 指定交互类型 
  name 是结果的 key
  message  标题
  default 默认值

  choices 每个选项
  loop  是否能够循环
*/

const res = await inquirer.prompt([
  {
    // 文本输入
    type: "input",
    name: "1",
    message: "问题=》1",
    default: "问题1 默认值",
  },
  {
    // 只能是数字
    type: "number",
    name: "2",
    message: "问题=》2",
    default: "问题2 因为输入非数字走了默认值",
  },
  {
    // 确认问题
    type: "confirm",
    name: "3",
    message: "问题=》3",
    default: false,
  },
  {
    // 选择列表--单选
    type: "list",
    name: "4",
    message: "问题=》4",
    default: 2,
    choices: ["选项1", "选项2", "选项3"],
    loop: true,
  },
  {
    type: "rawlist",
    name: "5",
    message: "问题=》5",
    default: 2,
    choices: ["选项1", "选项2", "选项3"],
    loop: true,
  },
  {
    type: "expand",
    name: "6",
    message: "问题=》6",
    choices: [
      { key: "z", name: "item-z", value: "item-v-z" },
      { key: "x", name: "item-x", value: "item-v-x" },
      { key: "c", name: "item-c", value: "item-v-c" },
    ],
    default: "x",
  },
  {
    // 选择列表--多选
    type: "checkbox",
    name: "7",
    message: "问题=》7",
    choices: ["a", "b", "c"],
    default: 1,
    loop: true,
  },
]);

console.log(res);
javascript
console.clear();
const { name } = await inquirer.prompt([
  {
    // 文本输入
    type: "input",
    name: "name",
    message: "请输入创建的项目名称",
    default: "aaa",
  },
]);

const bool = existsSync(path.resolve(process.cwd(), "./" + name));
if (bool) {
  const { ok } = await inquirer.prompt([
    {
      type: "confirm",
      name: "ok",
      message: `项目文件(${name})已经存在,是否要进行覆盖?`,
      default: true,
    },
  ]);

  if (!ok) {
    // throw `项目文件(${name})已经存在`
    console.log(`项目文件(${name})已经存在`);
    process.exit(0);
  }

  await rm(path.resolve(process.cwd(), "./" + name), {
    force: true,
    recursive: true,
  });
}

console.log("创建项目成功");