1. #!/usr/bin/env node
  2. const yargs = require('yargs/yargs');
  3. const dedent = require('dedent');
  4. const pkg = require('../package.json');
  5. const argv = process.argv.splice(2);
  6. const context = {
  7. wyyVersion: pkg.version,
  8. };
  9. const cli = yargs();
  10. cli
  11. // $0 会拿到 bin 下面的命令名称
  12. .usage('Usage: $0 [command] <options>')
  13. // 命令错误时候,提示类似的命令到shell窗口
  14. .recommendCommands()
  15. .demandCommand(1, '最少输入一个参数')
  16. // 严格模式,有无法识别的参数会给出提示
  17. .strict()
  18. .alias('h', 'help')
  19. .alias('v', 'version')
  20. // 全局 Options 添加选项
  21. .options({
  22. debug: {
  23. // 添加的选项名
  24. type: 'boolean',
  25. describe: 'debug mode',
  26. alias: 'd', // 别名
  27. },
  28. })
  29. // 选项分组
  30. .group(['debug'], 'Dev Options:')
  31. // 定义单个的 option
  32. .option('registry', {
  33. alias: 'r',
  34. type: 'string',
  35. description: 'Define global registry',
  36. // 是否隐藏
  37. // hidden: false
  38. })
  39. .command(
  40. // init 脚手架后面输入的名,[name]定义的option
  41. 'init [name]',
  42. // 命令描述
  43. 'Define name for a project',
  44. // builder,在执行这个command之前做的事情
  45. (yargs) => {
  46. yargs.option('name', {
  47. type: 'string',
  48. describe: 'init的option',
  49. alias: 'n',
  50. });
  51. },
  52. // handler,执行comand 的行为
  53. (argv) => {
  54. console.log('argv', argv);
  55. }
  56. )
  57. // 对象形式的定义
  58. .command({
  59. command: 'list',
  60. aliases: ['ls', 'la', 'll'],
  61. describe: 'list 的描述',
  62. builder: (yargs) => {},
  63. handler: (argv) => {
  64. console.log(argv);
  65. },
  66. })
  67. // terminalWidth返回当前shell窗口的宽度
  68. .wrap(cli.terminalWidth())
  69. // 设置结尾显示的内容
  70. .epilogue(
  71. dedent`
  72. When a command fails, all logs are written to lerna-debug.log in the current working directory.
  73. For more information, find our manual at https://github.com/lerna/lerna
  74. `
  75. )
  76. // 命令有误,错误提示
  77. .fail((msg, err) => {
  78. console.log(msg);
  79. })
  80. // 解析命令参数,合并传入的参数,合并完作为一个新的参数注入到脚手架中
  81. .parse(argv, context);

效果图

wyy -h
image.png

wyy init -n wy_name -r -d
image.png

输入错误的命令 wyy lis
image.png