[CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript
2023-09-14 08:59:14 时间
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
相关文章
- JS框架_(Vue.js)带有星期日期的数字时钟
- Node.js压缩与解压数据
- js定时器优化
- JS插件之——bootstrap-suggest.js
- [Typescript] Step1 & 2 for converting a js app to ts
- [Typescript] Use the Optional Chaining Operator in TypeScript
- [Node.js] Ways for Environment Variables
- [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
- [Typescript] Sorting arrays in TypeScript
- [Node.js] node-persist: localStorage on the server
- [Typescript] Get a TypeScript package ready for release to NPM
- [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
- [WASM] Run WebAssembly in Node.js using the node-loader
- [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types
- what is the location of js when using run as server in Eclipse
- Atitit 前端测试最简化内嵌web服务器 php 与node.js 目录 1.1. php内置Web Server1 1.2. Node的2 Node的比较麻烦些。。Php更加简单
- paip.编程语言方法重载实现的原理及python,php,js中实现方法重载
- 13 个 JS 数组精简技巧
- js之简易计算器
- Node.js(一)概述、全局对象/函数、node各模块使用介绍
- 【JS高级】js之正则相关函数以及正则对象_02
- 原生js实现随机验证码HTMl-JS
- 前端必备技能知识:JS导出Blob流文件为Excel表格、Vue.js使用Blob的方式实现excel表格的下载(流文件下载)