我正在尝试创建一个可以动态创建带有选项的子命令的 CLI。我有一个名为“仪表板”的主程序。我想创建具有选项的“登录”和“注销”子命令。我似乎无法运行子命令选项。它退出代码,说选项不存在。理想情况下使用 switch case,如果我想添加更多命令,那将是我唯一需要更改的地方。我怎样才能动态创建它?
我试过在主命令上使用 .hook() 来添加选项,但它对我没有用。我试过创建一个单独的可执行文件,但没有用。这是我目前所拥有的
// main command
const program = new Command();
program
.name("dashboard")
.description("CLI")
.option("-d, --debug", "outputs extra debugging", false)
.hook("preSubcommand", (commandObj) => {
if (commandObj.args[1] === "login") {
program.addOption(new Option("-e, --email")); // this doesn't work
}
});
program.parse(process.argv);
//subcommands
const commander = program.command("dashboard");
const subcommand = program.args[1];
try {
let func: any;
let description: string;
let option: any;
switch (subcommand) {
case "login":
description = "Logging you in!";
func = (await import("./commands/login.js")).default;
option = "-e, --email";
break;
case "logout":
description = "Logging you out";
func = (await import("./commands/logout.js")).default;
break;
default:
description = "";
func = null;
break;
}
commander
.command(subcommand)
.on("command:login", () => console.log("Does this work?")) // No, it doesn't
.hook("preSubcommand", () => {
if (subcommand === "login") {
console.log("What about this?"); // Still no
}
});
.description(description)
.option(option) // Tried adding the option from the switch case here, doesn't work
.action(async (arg, option) => {
console.log("🚀 ~ file: index.ts:128 ~ .action ~ option:", option);
console.log("test");
await func(client);
});
console.log("🚀 ~ file: index.ts:131 ~ main ~ commander:", commander.opts());
} catch (err: unknown) {
console.log(err);
}
program.parse();
当我运行命令
dashboard login -e
时,我得到一个错误:
error: unknown option '-e'
ELIFECYCLE Command failed with exit code 1.
如果没有给出选项,它将运行子命令,所以只需
dashboard login
就可以正常工作。否则,它会抛出上面的错误。