脚手架学习-yargs入门 (4)

这是我参与更文挑战的第4天,活动详情查看: 更文挑战

一、创建项目

仓库初始化

npm init -y
复制代码

创建bin目录,在目录下创建index.js文件

#!/usr/bin/env node
console.log('zl1-test')
复制代码

修改package.json

"bin": {
  "zl1-test": "bin/index.js"
},
复制代码

然后发布到npm上
通过 npm login 登录,npm publish发布

npm login
复制代码

输入账号,密码,邮箱号

发布

npm publish
复制代码

查看npm库是否有你的项目

拉取线上的项目

npm i -g zl1-test
复制代码

输入zl1-test,

image.png

项目初始化成功!

二、使用yargs

安装yargs

npm i -S yargs
复制代码

在bin/index.js目录编写代码

输出–help或–version,能在yargs中拿到

const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

const arg = hideBin(process.argv)
console.log(hideBin(process.argv))

yargs(arg).argv

复制代码

输入zl1-test –help,查看结果

image.png

以上是它简单的使用记录

为yargs添加多个命令,yargs的地址是:www.npmjs.com/package/yar…

  1. usage: 用法格式
  2. alias:给命令起别名
  3. wrap: 修改间距宽度
  4. demandCommand: 输入参数的最小个数
  5. epilogue:在帮助信息尾部显示
const cli = yargs(arg)
cli
  .usage('zl1-test [command] <options>')
  .demandCommand(1, 'A command is required. Pass --help to see all available commands and options.')// 提示文字
  .strict()
  .alias('h', 'help')
  .alias('v', 'version')
  // .wrap(cli.terminalWidth()) //修改宽度
  .epilogue('Your own footer description')
  .argv
复制代码

安装dedent,它的作用是从多行字符串中去除缩进的 ES6 字符串标签。

npm i -S dedent
复制代码

使用

const dedent = require('dedent')

const cli = yargs(arg)
cli
  .usage('zl1-test [command] <options>')
  .demandCommand(1, 'A command is required. Pass --help to see all available commands and options.')// 提示文字
  .strict()
  .alias('h', 'help')
  .alias('v', 'version')
  // .wrap(cli.terminalWidth()) //修改宽度
  .epilogue(dedent`when a command fails, all logs are written to lerna-debug.log in the current working directory.
  
  For more information, find our manual at https://githup.com/lerna/lerna`)
  .options({
    debug: {
      type: 'boolean',
      describe: 'Bootstrap debug mode',
      alias: 'd'
    }
  })
  .option('registry', {
    type: 'string',
    describe: 'Define global registry',
    alias: 'r'
    // hidden: true,
  })
  .group(['debug'], 'Dev Options:')
  .group(['registry'], 'Extra Options:')
  .argv
复制代码

三、使用command

command注册命令,有四个参数,分别是

  1. cmd:代表是命令的名称或者别名
  2. desc:描述作用
  3. builder: 提示命令需要接收的参数
  4. handler:调用并且传入处理过的argv

第一种使用方式

.command('init [name]', 'Do init a project', (yargs) => {
    yargs
      .option('name', {
        type: 'string',
        describe: 'Name of a project',
        alias: 'n'
      })
  }, (argv) => {
    console.log(argv)
  })
复制代码

第二种

.command({
    command: 'list',
    aliases: ['ls', 'la', 'll'],
    describe: 'List local packages',
    builder: (yargs) => {},
    handler: (argv) => { console.log(argv) }
  })
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享