进阶 oclif.io 2026-10-18 02:37:03 · 28 阅读
第42章 程序化运行命令
程序化运行命令
如果需要从一个命令中运行另一个命令,或在其他代码库中以编程方式执行命令,有几种不同的选择。
首先,直接调用命令通常不是一个好主意,因为命令暴露的是用户界面,而非代码接口。这是一种设计缺陷,几乎(如果有的话)不应该被使用。一般来说,更好的做法是拆分代码,使其能够被直接调用,而不是通过命令的形式。下面我们先介绍这种更优的方法。
使用模块共享代码
例如,假设你有一个 config list 命令,用于将应用的配置变量输出到终端。
./src/commands/config/list.ts
export class ConfigList extends Command {
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigList)
const config = await api.get(`/apps/${flags.app}/config-vars`)
for (let [key, value] of Object.entries(config)) {
this.log(`${key}=${value}`)
}
}
}
再假设你有另一个命令,config update,它更新应用的配置,最后将新的配置变量显示在终端上。
由于 config list 和 config update 都需要以完全相同的方式显示配置变量,你应该创建一个负责生成显示效果的新模块、函数或类。
例如:
./src/commands/config/update.ts
import {displayConfigVars} from '../displayConfigVars'
export class ConfigUpdate extends Command {
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigUpdate)
await this.doUpdate(flags.app)
await displayConfigVars(flags.app)
}
}
./src/displayConfigVars.ts
export async function displayConfigVars(app: string) {
const config = await api.get(`/apps/${app}config-vars`)
for (let [key, value] of Object.entries(config)) {
this.log(`${key}=${value}`)
}
}
这是官方推荐的代码共享方式。更进一步,你还可以把共享代码抽成独立的 npm 包。
直接调用命令
不过,如果你确实想直接调用某个命令,也并不难,主要有两种方式。
第一种:如果你确定要运行的命令已安装在 CLI 中,可以使用 this.config.runCommand。比如配置更新命令可以这样写:
./src/commands/config/update.ts
export class ConfigUpdate extends Command {
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigUpdate)
await this.doUpdate(flags.app)
await this.config.runCommand('config:list', ['--global'])
}
}
第二种:直接导入命令类并执行它,如下所示: ./src/commands/config/update.ts import {ConfigList} from './config/list'
export class ConfigUpdate extends Command {
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigUpdate)
await this.doUpdate(flags.app)
await ConfigList.run(['--global'])
}
}
之所以可行,是因为每个命令类都有一个静态的 .run() 方法,它会实例化命令并调用实例的 .run() 方法,入参是传给命令的 argv。 但还是要再强调一遍:我们强烈建议避免这两种做法。更好的方式是把共享逻辑从 Command 类中抽离出来。
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigUpdate)
await this.doUpdate(flags.app)
await this.config.runCommand('config:list', ['--global'])
}
}
第二种:直接导入命令类并执行它,如下所示: ./src/commands/config/update.ts import {ConfigList} from './config/list'
export class ConfigUpdate extends Command {
static flags = {
app: Flags.string({required: true})
}
async run() {
const {flags} = await this.parse(ConfigUpdate)
await this.doUpdate(flags.app)
await ConfigList.run(['--global'])
}
}
之所以可行,是因为每个命令类都有一个静态的 .run() 方法,它会实例化命令并调用实例的 .run() 方法,入参是传给命令的 argv。 但还是要再强调一遍:我们强烈建议避免这两种做法。更好的方式是把共享逻辑从 Command 类中抽离出来。