如何为yargs子命令的自动生成帮助信息添加Epilogue?
解决Yargs子命令帮助信息不显示全局Epilogue的问题
问题场景
使用TypeScript结合Yargs开发命令行应用时,通过全局.epilogue()设置的结语仅在顶层帮助信息(直接运行--help)中生效,但在子命令的帮助信息(如whatever --help)中不会显示。
原代码
import yargs from 'yargs'; yargs(process.argv.slice(2)) .command({ command: 'whatever', describe: 'Do something', builder: (argv: yargs.Argv) => argv.options({}), }) .help() .epilogue('Report bugs at ...') .parse();
现象
- 顶层帮助正常显示结语:
$ node --import=tsx src/index.ts --help index.ts [command] Commands: zzzso.ts whatever Do something Options: --version Show version number [boolean] --help Show help [boolean] Report bugs at ...
- 子命令帮助无结语:
$ node --import=tsx src/index.ts whatever --help index.ts whatever Do something Options: --version Show version number [boolean] --help Show help [boolean]
解决方法
Yargs的全局epilogue()不会自动继承到子命令,需要在每个子命令的builder中显式设置结语。
方法1:直接在子命令builder中添加epilogue
将结语内容定义为常量,在全局和子命令中复用:
import yargs from 'yargs'; // 定义全局结语常量 const EPILOGUE = 'Report bugs at ...'; yargs(process.argv.slice(2)) .command({ command: 'whatever', describe: 'Do something', builder: (argv: yargs.Argv) => argv.options({}).epilogue(EPILOGUE), // 子命令中添加结语 }) .help() .epilogue(EPILOGUE) // 全局设置结语 .parse();
方法2:提取公共builder函数(多子命令场景)
如果有多个子命令,可封装公共builder函数避免重复代码:
import yargs from 'yargs'; const EPILOGUE = 'Report bugs at ...'; // 公共builder:添加通用配置和结语 const commonBuilder = (argv: yargs.Argv) => { return argv.options({}).epilogue(EPILOGUE); }; yargs(process.argv.slice(2)) .command({ command: 'whatever', describe: 'Do something', builder: commonBuilder, }) .command({ command: 'another', describe: 'Do another thing', builder: commonBuilder, }) .help() .epilogue(EPILOGUE) .parse();
修改后效果
运行子命令帮助时会正常显示结语:
$ node --import=tsx src/index.ts whatever --help index.ts whatever Do something Options: --version Show version number [boolean] --help Show help [boolean] Report bugs at ...
内容的提问来源于stack exchange,提问作者Guido Flohr
相关产品推荐
相关产品推荐

