zoukankan      html  css  js  c++  java
  • [CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript

    Sometimes you still want to support the API and quick developer experience of a single command, while still supporting multi commands in your CLI. This is handy when, for example, you want your user to do something useful with just npx mycli.

    Here's a quick hack that lets you do that, while also deepening your understanding of how your CLI works with TypeScript, Node.js and Oclif under the hood.

    If we have multi commands, when we run:

    yarn mycli

    It will just list all the commands we have here:

    Now, let's say, we want to set 'init' command as default command.

    What we can do:

    // bin/run.js
    #!/usr/bin/env node
    
    const fs = require('fs')
    const path = require('path')
    const project = path.join(__dirname, '../tsconfig.json')
    const dev = fs.existsSync(project)
    
    if (dev) {
      require('ts-node').register({project})
    }
    
    const recongnizedCommand = ['init', 'build']
    if (process.argv.length > 2 && recongnizedCommand.includes(process.argv[2])) {
      require(`../${dev ? 'src' : 'lib'}`).run()
      .catch(require('@oclif/errors/handle'))
    } else {
      require(`../${dev ? 'src' : 'lib'}/commands/init`).run()
      .catch(require('@oclif/errors/handle'))
    }

    Now, if we just run:

    yarn mycli
    
    // the same as
    
    yarn mycli init
  • 相关阅读:
    闲着写了一个查看股票的程序
    Oracle10g正则表达式
    跨语言平台的RSA加密、解密、签名、验证算法的实现
    Base64转换:AQAB=65537,你知道为什么吗?
    无题
    07年了,新的一年又开始了
    简单生活
    近期关注
    闲话
    各大网站的WEB服务器分析
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12391888.html
Copyright © 2011-2022 走看看