通过使用 typescript 和 OCLIF 创建您自己的 CLI 命令来提高您的工作效率(第 2 部分)🚀
上下文
OCLIF是一个出色的框架,可以轻松开发专业的 CLI 命令。让我们看看如何在不到 3 分钟的时间内创建一个让最终用户满意的 CLI 命令。
最终项目发布于https://github.com/raphaelmansuy/matcha-stock
如果您喜欢本教程,请在项目上添加 🌟 ❤️
$ matcha-stock -symbol=MSFT
进入全屏模式 退出全屏模式
走吧! 🚀
使用 OCLIF 创建新命令(30 秒⏰)
npx oclif single matcha-stock
cd matcha-stock
./bin.run
进入全屏模式 退出全屏模式
结果:
OCLIF 为我的命令生成一个启动项目。
❯ npx oclif single matcha-stock
_-----_ ╭──────────────────────────╮
| | │ Time to build a │
|--(o)--| │ single-command CLI with │
`---------´ │ oclif! Version: 1.16.1 │
( _´U`_ ) ╰──────────────────────────╯
/___A___\ /
| ~ |
__'.___.'__
´ ` |° ´ Y `
npm package name matcha-stock
? command bin name the CLI will export matcha-stock
? description A command to get stocks information
? author Raphael MANSUY @raphaelmansuy
? version 0.0.1
? license MIT
? Who is the GitHub owner of repository (https://github.com/OWNER/repo) raphaelmansuy
? What is the GitHub name of repository (https://github.com/owner/REPO) matcha-stock
? Select a package manager yarn
? TypeScript Yes
? Use eslint (linter for JavaScript and Typescript) Yes
? Use mocha (testing framework) Yes
进入全屏模式 退出全屏模式
由 OCLIF 创建的代码
├── README.md
├── bin
│ ├── run
│ └── run.cmd
├── package.json
├── src
│ └── index.ts
├── test
│ ├── index.test.ts
│ ├── mocha.opts
│ └── tsconfig.json
├── tsconfig.json
└── yarn.lock
进入全屏模式 退出全屏模式
src/index.ts的内容
import { Command, flags } from "@oclif/command"
class MatchaStock extends Command {
static description = "describe the command here"
static flags = {
// add --version flag to show CLI version
version: flags.version({ char: "v" }),
help: flags.help({ char: "h" }),
// flag with a value (-n, --name=VALUE)
name: flags.string({ char: "n", description: "name to print" }),
// flag with no value (-f, --force)
force: flags.boolean({ char: "f" })
}
static args = [{ name: "file" }]
async run() {
const { args, flags } = this.parse(MatchaStock)
const name = flags.name ?? "world"
this.log(`hello ${name} from ./src/index.ts`)
if (args.file && flags.force) {
this.log(`you input --force and --file: ${args.file}`)
}
}
}
export = MatchaStock
进入全屏模式 退出全屏模式
✅ OCLIF 创建了一个模板类来代表我的命令框架。
从生成的代码开始,我可以:
-
💪 添加 flags 例如
--symbol -
🏗 修改**
run()**方法的实现
添加标志--symbol的支持(40秒⏰)
import { Command, flags } from "@oclif/command"
class MatchaStock extends Command {
static description =
"A simple command to retrieve stock information from Yahoo Finance"
static flags = {
// add --version flag to show CLI version
version: flags.version({ char: "v" }),
help: flags.help({ char: "h" }),
// Add Support of of -symbol flag
// flag with a value (-s, --symbol=VALUE)
symbol: flags.string({
char: "s", // Alias for my flag
description: "stock symbol to retrieve", // A description of the symbol flag
required: true, // The flag symbol is required 👉 The command will abort of the flag is not provide
helpValue: "MSFT" // An example of flag value (MSFT is the symbol for Microsoft)
})
}
async run() {
const { args, flags } = this.parse(MatchaStock)
this.log(`Get Symbol=${flags.symbol} from ./src/index.ts`)
}
}
export = MatchaStock
进入全屏模式 退出全屏模式
我现在可以测试我的命令
✅ 没有旗帜
./bin
进入全屏模式 退出全屏模式
结果:
› Error: Missing required flag:
› -s, --symbol SYMBOL stock symbol to retrieve
› See more help with --help
进入全屏模式 退出全屏模式
✅ 带标志 -help
./bin -help
进入全屏模式 退出全屏模式
结果:
❯ ./bin/run -help
A simple command to retrieve stock information from Yahoo Finance
USAGE
\$ matcha-stock
OPTIONS
-h, --help show CLI help
-s, --symbol=MSFT (required) stock symbol to retrieve
-v, --version show CLI version
进入全屏模式 退出全屏模式
✅ 带标志--symbol
./bin --symbol GOOG
进入全屏模式 退出全屏模式
结果:
❯ ./bin/run -symbol=GOOG
Get Symbol=ymbol=GOOG from ./src/index.ts
进入全屏模式 退出全屏模式
添加业务逻辑(60秒⏰)
👉 添加axios作为我们的 http 库。
yarn add axios
进入全屏模式 退出全屏模式
👉 添加文件./src/getStock.ts
import axios from "axios"
export const getSingleStockInfo = async (stock: string) => {
if (!stock) {
throw new Error("Stock symbol argument required")
}
if (typeof stock !== "string") {
throw new Error(
`Invalid argument type for stock argument. Required: string. Found: ${typeof stock}`
)
}
const url = `https://query1.finance.yahoo.com/v7/finance/quote?symbols=${stock}`
const res = await axios.get(url)
const { data } = res
if (
!data ||
!data.quoteResponse ||
!data.quoteResponse.result ||
data.quoteResponse.result.length === 0
) {
throw new Error(`Error retrieving info for symbol ${stock}`)
}
const quoteResponse = data.quoteResponse.result[0]
return quoteResponse
}
进入全屏模式 退出全屏模式
👉 修改src/index.ts文件如:
import { Command, flags } from "@oclif/command"
import { getSingleStockInfo } from "./getStocks"
class MatchaStock extends Command {
static description = `A simple command to retrieve stock information from Yahoo Finance.\nA simple command to retrieve stock information from Yahoo Finance.\n\n Created with ❤️ by Elitizon (https://www.elitizon.com)`
static flags = {
// add --version flag to show CLI version
version: flags.version({ char: "v" }),
help: flags.help({ char: "h" }),
// Add Support of of -symbol flag
// flag with a value (-s, --symbol=VALUE)
symbol: flags.string({
char: "s", // Alias for my flag
description: "stock symbol to retrieve", // A description of the symbol flag
required: true, // The flag symbol is required 👉 The command will abort of the flag is not provide
helpValue: "MSFT" // An example of flag value (MSFT is the symbol for Microsoft)
})
}
async run() {
const { flags } = this.parse(MatchaStock)
const res = await getSingleStockInfo(flags.symbol)
// Print the result as tabular
console.table(res)
}
}
export = MatchaStock
进入全屏模式 退出全屏模式
👉 测试命令
❯ ./bin/run -s=MSFT
┌───────────────────────────────────┬─────────────────────────┐
│ (index) │ Values │
├───────────────────────────────────┼─────────────────────────┤
│ language │ 'en-US' │
│ region │ 'US' │
│ quoteType │ 'EQUITY' │
│ quoteSourceName │ 'Delayed Quote' │
│ triggerable │ true │
│ currency │ 'USD' │
│ firstTradeDateMilliseconds │ 511108200000 │
│ priceHint │ 2 │
│ marketState │ 'POSTPOST' │
│ postMarketChangePercent │ 0.31417143 │
进入全屏模式 退出全屏模式
发布命令到NPM.org(30秒⏰)
npm publish
进入全屏模式 退出全屏模式
✅ 该软件包现已发布在npm.orghttps://www.npmjs.com/package/matcha-stock
-
👉 如果包已经在NPM上注册,你必须更改包的名称。
-
👉 每次发布都必须更新包版本
测试你的命令(10 秒⏰)
npm install -g matcha-stock
matcha-stock -s=MSFT
进入全屏模式 退出全屏模式
结论
OCLIF是一个令人印象深刻的框架。使用 OCLIF 可以轻松创建:
-
单命令 CLI
-
多命令 CLI
主要特点:
-
🕺 标志/参数解析
-
🚀 超高速
-
🏗 包含一个 CLI 生成器以加速命令的开发
-
测试助手
-
自动文档
-
插件
-
挂钩
OCLIF 在Github上可用,由Matt Graham 维护、Paul Elliott和Chris Castle并由[Heroku8 6 10008🎉8 10008 资助
更多推荐

所有评论(0)