使用typescript快速開發(fā)一個cli的實現(xiàn)示例
cli 的全稱 command-line interface(命令行界面),也就是前端同學(xué)常用的腳手架,比如 yo、vue cli、react cli 等。
cli 可以方便我們快速創(chuàng)建項目,下圖是引用 vue cli 的介紹:

創(chuàng)建項目
運(yùn)行下面的命令,創(chuàng)建一個項目:
npm init
執(zhí)行命令完成后,可以看到項目根目錄只有一個 package.json 文件。

在 package.json 文件增加 bin 對象,并指定入口文件 dist/index.js。
在命令行運(yùn)行需要在入口文件的第一行增加 #!/usr/bin/env node,告訴系統(tǒng)用 node 運(yùn)行這個文件。
{
"name": "cli-demo",
"version": "0.0.1",
"description": "cli demo",
"keywords": [
"cli"
],
"bin": {
"cli-demo": "dist/index.js"
}
...
}
安裝依賴
命令行工具,也會涉及到用戶交互的動作,那么 node.js 是怎么實現(xiàn)呢?早有大佬提供了非常好的庫,我們只要拿過來用,主要有兩個庫:
將這兩個庫安裝到項目里:
yarn add commander inquirer
由于是用 typescript 開發(fā),再通過 rollup 打包,先安裝相關(guān)的依賴庫:
yarn add typescript rollup rollup-plugin-terser rollup-plugin-typescript2 @types/inquirer -D
配置
由于是用 typescript 開發(fā),首先需要配置一下 tsconfig.json。
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"sourceMap": false,
"declaration": false,
"outDir": "./dist",
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true,
"removeComments": false,
"importHelpers": true,
"strict": true,
"lib": ["ES6", "DOM"]
},
"include": ["src"]
}
接下來在根目錄增加一個 rollup.config.js,把 typescript 代碼編譯成 javascript 代碼。前面提到的要在第一行增加 #!/usr/bin/env node 來告訴系統(tǒng)用 node 運(yùn)行,那么可以在 rollup.config.js 的 banner 選項,把 #!/usr/bin/env node 寫在最前面。
import typescript from 'typescript'
import json from '@rollup/plugin-json'
import { terser } from 'rollup-plugin-terser'
import typescript2 from 'rollup-plugin-typescript2'
import { dependencies } from './package.json'
const external = Object.keys(dependencies || '')
const globals = external.reduce((prev, current) => {
const newPrev = prev
newPrev[current] = current
return newPrev
}, {})
const defaultConfig = {
input: './src/index.ts',
output: {
file: './dist/index.js',
format: 'cjs',
banner: '#!/usr/bin/env node',
globals
},
external,
plugins: [
typescript2({
exclude: 'node_modules/**',
useTsconfigDeclarationDir: true,
typescript,
tsconfig: './tsconfig.json'
}),
json(),
terser()
]
}
export default defaultConfig
實現(xiàn)一個簡單的 cli
在根目錄創(chuàng)建一個 src 文件夾,然后再創(chuàng)建一個 index.ts。
添加引用
添加引用并實例化 Command 對象。
import { Command } from 'commander'
import pkg from '../package.json'
const program = new Command(pkg.name)
自定義命令
實現(xiàn)一個可交互的自定義命令,模擬在終端(命令行)的登錄功能。使用 command 方法創(chuàng)建一個命令,description 可以用來描述這個命令的作用,登錄處理邏輯則寫在 action 方法里。最后使用 parse(process.argv) 方法,解析命令。更多詳細(xì)介紹和使用,可移步:https://github.com/tj/commander.js/blob/master/Readme_zh-CN.md。
program
.command('login')
.description('模擬登錄。')
.action(() => {
handleLogin()
})
program.parse(process.argv)
交互的話,用到前面說的 inquirer 庫,接收輸入的用戶名和密碼。選項的 type 的值有 input、password、number、checkbox、editor、list、rawList、expand、confirm,選項 name 是 inquirer.prompt 方法返回的對象,選項 validate 可用來驗證輸入是否符合規(guī)則。更多詳細(xì)介紹和使用,可移步:https://github.com/SBoudrias/Inquirer.js/blob/master/README.md
如果選項 type 是 password,可通過 mask 設(shè)置掩碼。
const handleLogin = () => {
// 配置交互的用戶名和密碼
const prompt = [
{
type: 'input',
name: 'userName',
message: '用戶名:',
validate: (value: string) => value.length > 0 || '用戶名不能為空'
},
{
type: 'password',
name: 'password',
message: '密碼:',
mask: '🙈 ',
validate: (value: string) => value.length > 0 || '密碼不能為空'
}
]
inquirer.prompt(prompt).then(({ userName, password }) => {
if (userName === 'demo' || password === '123456') {
console.log('登錄成功')
return
}
console.log('用戶名或密碼錯誤')
})
}
其他
一個 cli 工具,幫助信息也是必須的,可以通過 on('--help') 修改自定義幫助信息。
必須在 parse 方法之前。
program.on('--help', () => {
console.log('\n運(yùn)行 cli-demo -h | --help 查看命令使用。\n')
})
然后再來修改一下,沒有輸入任何參數(shù)的時候,會出現(xiàn)錯誤,可以使用 exitOverride 方法重新退出,在終端(命令行)輸出幫助信息。
program.exitOverride()
try {
program.parse(process.argv)
} catch (error) {
program.outputHelp()
}
到這里,一個簡單的 cli 工具完成了,先本地來測試下看看。在終端(命令行)輸入 npm link,生成一個全局軟連接,可以方便調(diào)試和測試。

到此這篇關(guān)于使用typescript快速開發(fā)一個cli的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)typescript開發(fā)cli內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
給應(yīng)用部分的js代碼設(shè)定一個統(tǒng)一的入口
javascript是種腳本語言,瀏覽器下載到哪兒就會執(zhí)行到哪兒,下面為大家介紹下,如何給應(yīng)用部分的js代碼一個統(tǒng)一的入口2014-06-06
css transform 3D幻燈片特效實現(xiàn)步驟解讀
3D幻燈片特效想必大家以不在陌生至于表現(xiàn)形式一般都是拘泥于傳統(tǒng)接下來為大家介紹下使用css3 transform配合js以及html實現(xiàn)3D幻燈片特效2013-03-03
詳解微信小程序自定義組件的實現(xiàn)及數(shù)據(jù)交互
這篇文章主要介紹了微信小程序自定義組件的實現(xiàn)及數(shù)據(jù)交互,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
檢查輸入的是否是數(shù)字使用keyCode配合onkeypress事件
檢查輸入的是否是數(shù)字在本文使用keyCode配合onkeypress事件來實現(xiàn),具體示例如下2014-01-01
Javascript的數(shù)組與字典用法與遍歷對象的技巧
Javascript 的數(shù)組Array,既是一個數(shù)組,也是一個字典(Dictionary)。先舉例看看數(shù)組的用法2012-11-11

