进阶 oclif.io 2026-10-18 02:37:03 · 28 阅读
第35章 JSON 支持
# 第35章 JSON
如果想通过 --json 标志向用户返回 JSON 格式的输出,可以在 Command 类上设置 enableJsonFlag 属性。
设置该属性后,用户只要加上 --json 标志,命令就会屏蔽所有日志,改为以 JSON 格式把返回值打印到控制台。注意,日志屏蔽只对 Command 类实例上的日志方法生效——也就是说,this.log 会被自动屏蔽,而 console.log 不会。
import {Command} from '@oclif/core'
export class HelloCommand extends Command {
public static enableJsonFlag = true
public async run(): Promise<{ message: string }> {
this.log('hello, world!')
return { message: 'hello, world!' }
}
}
$ my-cli hello
hello, world!
$ my-cli hello --json
{
"message": "hello, world!"
}
export class HelloCommand extends Command {
public static enableJsonFlag = true
public async run(): Promise<{ message: string }> {
this.log('hello, world!')
return { message: 'hello, world!' }
}
}
$ my-cli hello
hello, world!
$ my-cli hello --json
{
"message": "hello, world!"
}