进阶 oclif.io 2026-10-18 02:37:03 · 22 阅读

第25章 Flag 继承机制详解

### 第 25 章:Flag 继承 有时你可能希望为所有命令统一定义某个 flag。此时,你可以在抽象基类 Command 中添加一个基础 flag。例如: ```html import { Command, Flags } from '@oclif/core';

export abstract class BaseCommand extends Command {
static baseFlags = {
interactive: Flags.boolean({
char: 'i',
description: '以交互模式运行命令',
// 在帮助中,将此 flag 显示在一个单独的 GLOBAL 部分下。
helpGroup: 'GLOBAL',
}),
};
}
``` 所有继承自 BaseCommand 的命令现在都将拥有 `--interactive` flag。 如果你打算堆叠多层抽象 Command 类,则必须展开(spread)baseFlags,以确保 flag 能被正确继承。例如: ```html import { Command, Flags } from '@oclif/core';

export abstract class FirstBaseCommand extends Command {
static baseFlags = {
interactive: Flags.boolean({
char: 'i',
description: '以交互模式运行命令',
// 在帮助中,将此 flag 显示在一个单独的 GLOBAL 部分下。
helpGroup: 'GLOBAL',
}),
};
}

export abstract class SecondBaseCommand extends FirstBaseCommand {
static baseFlags = {
...FirstBaseCommand.baseFlags,
'log-level': Flags.option({
default: 'info',
description: '指定日志级别',
helpGroup: 'GLOBAL',
options: ['debug', 'warn', 'error', 'info', 'trace'] as const,
summary: '指定日志级别。',
char: 'l',
})(),
};
}

export abstract class ThirdBaseCommand extends SecondBaseCommand {
static baseFlags = {
...SecondBaseCommand.baseFlags,
verbose: Flags.boolean({
description: '显示详细输出。',
char: 'v'
})
};
}
```

评论 (0)