进阶 oclif.io 2026-10-18 02:37:03 · 24 阅读
第17章 Oclif命令开发指南
命令
一条基本的 TypeScript 命令如下所示:
import {Command} from '@oclif/core'
export class MyCommand extends Command {
static description = 'description of this example command'
async run(): Promise {
console.log('running my command')
}
}
唯一必需的部分是 run 函数。通过参数和标志(flags)接收用户输入。 在 JavaScript 中: const {Command} = require('@oclif/core')
class MyCommand extends Command {
async run() {
console.log('running my command')
}
}
MyCommand.description = 'description of this example command'
module.exports = MyCommand
请注意,以下示例均使用 TypeScript 编写。由于 JavaScript 尚不支持静态类属性,你必须在类声明之后手动添加这些属性,就像上面处理 description 那样。 避免超时 为了防止命令执行陷入无限循环,oclif 会在 Command.run 解析完成后 10 秒终止 node 进程。这意味着 run 方法内的所有命令逻辑要么同步执行,要么返回一个 Promise。这样可确保在 10 秒超时开始计时之前,整个命令运行完毕。 换言之,如果你在 Command.run 中执行了 Promise 却未 await 它,命令很可能会在完成前就超时。 其他命令选项 查看基类可了解命令上可调用哪些方法。 import {Command, Flags} from '@oclif/core'
export class MyCommand extends Command {
static summary = 'A brief overview of your command.'
static description = `
An in-depth description of the command.
It can be multiline.
`
// hide the command from help
static hidden = false
// custom usage string for help
// this overrides the default usage
static usage = 'mycommand --myflag'
// examples to add to help
// <%= config.bin %> resolves to the executable name
// <%= command.id %> resolves to the command name
static examples = [
// Examples can be simple strings
'<%= config.bin %> <%= command.id %> --help',
// Or objects that provide a description of the example command
{
description: 'Force the command to execute',
command: '<%= config.bin %> <%= command.id %> --force',
}
]
// this makes the parser not fail when it receives invalid arguments
Command Methods Command Methods this.log(message: string) this.warn(message: string | Error) this.error(message: string | Error, options?: {code?: string, exit?: number, ref?: string; suggestions?: string[];}) this.exit(code: number = 0) this.logToStderr(message: string) this.jsonEnabled() this.toSuccessJson(result: unknown) this.toErrorJson(result: unknown) 以下示例假设代码位于 oclif 命令的 run() 方法内。 this.log(message: string) 向 stdout 输出消息(非阻塞)。console.log() 也可以使用,但它是阻塞调用,且在存在 --json 标志时不会被自动抑制。此方法使用 util.format(),其行为与 console.log() 一致。 ``` this.log('hello, world!') ``` this.warn(message: string | Error) 将错误信息或消息作为警告显示 ``` this.warn('uh oh!') this.warn(new Error('uh oh!')) ``` this.error(message: string | Error, options?: {code?: string, exit?: number, ref?: string; suggestions?: string[];}) 显示错误信息并退出。还可以向错误对象添加代码或设置退出状态码。 ``` this.error('uh oh!', {exit: 2}) this.error(new Error('uh oh!')) ``` options 对象包含以下选项: exit — 要使用的退出码 code — 该错误类型的唯一错误码 suggestions — 一组建议,提示用户接下来可以尝试的操作,可能有用或提供额外的上下文 ref — 与该错误或其修复方法相关的文档链接 错误展示时,会显示 message、code、suggestions、ref 这些属性。你可以实现 @oclif/core 的 Errors 命名空间中的 PrettyPrintableError 接口,创建可复用的 Error 类来展示上述可选输出,this.error 会自动正确处理它们。 这类错误是友好的,除非通过 DEBUG=* 开启调试,否则不会显示堆栈跟踪。 import {CLIError} from '@oclif/errors'
throw new CLIError('my friendly error')
命令捕获到的任何 CLIError 类型的错误都会直接展示,不带堆栈跟踪。 this.exit(code: number = 0) 退出进程,默认状态码为 0。 this.exit()
this.exit(1)
this.logToStderr(message: string) 将消息输出到终端的 stderr。 this.jsonEnabled() 如果传入了 --json 标志且 enableJsonFlag 设为 true,则返回 true。 this.toSuccessJson(result: unknown) 在成功 JSON 输出展示给用户之前对其进行修改。 this.toErrorJson(result: unknown) 在错误 JSON 输出展示给用户之前对其进行修改。
export class MyCommand extends Command {
static description = 'description of this example command'
async run(): Promise
console.log('running my command')
}
}
唯一必需的部分是 run 函数。通过参数和标志(flags)接收用户输入。 在 JavaScript 中: const {Command} = require('@oclif/core')
class MyCommand extends Command {
async run() {
console.log('running my command')
}
}
MyCommand.description = 'description of this example command'
module.exports = MyCommand
请注意,以下示例均使用 TypeScript 编写。由于 JavaScript 尚不支持静态类属性,你必须在类声明之后手动添加这些属性,就像上面处理 description 那样。 避免超时 为了防止命令执行陷入无限循环,oclif 会在 Command.run 解析完成后 10 秒终止 node 进程。这意味着 run 方法内的所有命令逻辑要么同步执行,要么返回一个 Promise。这样可确保在 10 秒超时开始计时之前,整个命令运行完毕。 换言之,如果你在 Command.run 中执行了 Promise 却未 await 它,命令很可能会在完成前就超时。 其他命令选项 查看基类可了解命令上可调用哪些方法。 import {Command, Flags} from '@oclif/core'
export class MyCommand extends Command {
static summary = 'A brief overview of your command.'
static description = `
An in-depth description of the command.
It can be multiline.
`
// hide the command from help
static hidden = false
// custom usage string for help
// this overrides the default usage
static usage = 'mycommand --myflag'
// examples to add to help
// <%= config.bin %> resolves to the executable name
// <%= command.id %> resolves to the command name
static examples = [
// Examples can be simple strings
'<%= config.bin %> <%= command.id %> --help',
// Or objects that provide a description of the example command
{
description: 'Force the command to execute',
command: '<%= config.bin %> <%= command.id %> --force',
}
]
// this makes the parser not fail when it receives invalid arguments
Command Methods Command Methods this.log(message: string) this.warn(message: string | Error) this.error(message: string | Error, options?: {code?: string, exit?: number, ref?: string; suggestions?: string[];}) this.exit(code: number = 0) this.logToStderr(message: string) this.jsonEnabled() this.toSuccessJson(result: unknown) this.toErrorJson(result: unknown) 以下示例假设代码位于 oclif 命令的 run() 方法内。 this.log(message: string) 向 stdout 输出消息(非阻塞)。console.log() 也可以使用,但它是阻塞调用,且在存在 --json 标志时不会被自动抑制。此方法使用 util.format(),其行为与 console.log() 一致。 ``` this.log('hello, world!') ``` this.warn(message: string | Error) 将错误信息或消息作为警告显示 ``` this.warn('uh oh!') this.warn(new Error('uh oh!')) ``` this.error(message: string | Error, options?: {code?: string, exit?: number, ref?: string; suggestions?: string[];}) 显示错误信息并退出。还可以向错误对象添加代码或设置退出状态码。 ``` this.error('uh oh!', {exit: 2}) this.error(new Error('uh oh!')) ``` options 对象包含以下选项: exit — 要使用的退出码 code — 该错误类型的唯一错误码 suggestions — 一组建议,提示用户接下来可以尝试的操作,可能有用或提供额外的上下文 ref — 与该错误或其修复方法相关的文档链接 错误展示时,会显示 message、code、suggestions、ref 这些属性。你可以实现 @oclif/core 的 Errors 命名空间中的 PrettyPrintableError 接口,创建可复用的 Error 类来展示上述可选输出,this.error 会自动正确处理它们。 这类错误是友好的,除非通过 DEBUG=* 开启调试,否则不会显示堆栈跟踪。 import {CLIError} from '@oclif/errors'
throw new CLIError('my friendly error')
命令捕获到的任何 CLIError 类型的错误都会直接展示,不带堆栈跟踪。 this.exit(code: number = 0) 退出进程,默认状态码为 0。 this.exit()
this.exit(1)
this.logToStderr(message: string) 将消息输出到终端的 stderr。 this.jsonEnabled() 如果传入了 --json 标志且 enableJsonFlag 设为 true,则返回 true。 this.toSuccessJson(result: unknown) 在成功 JSON 输出展示给用户之前对其进行修改。 this.toErrorJson(result: unknown) 在错误 JSON 输出展示给用户之前对其进行修改。