十分鐘通過 NPM 建立一個命令列工具
寫了一個小 demo,用於代替 touch
的建立檔案命令 touchme
,可以建立自帶“佛祖保佑”註釋的檔案。效果如下:
命令可以帶有一個引數,選擇註釋的符號
現在,開始擼程式碼 ~
首先建立一個資料夾,我起名字 create-file-cli
然後通過 npm init
命令建立 package.json
檔案。
$ mkdir create-file-cli $ cd create-file-cli $ npm init -y
然後修改 package.json
新增一個 bin
欄位,定義一個 touchme
命令,並指定該命令執行的檔案。
{ "name": "create-file-cli", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "bin": { "touchme": "bin/touchme.js" }, "keywords": [], "author": "", "license": "ISC" }
接下來實現 bin/touchme.js
,要用到 Commander.js -- node.js 命令列介面的完整解決方案。看不懂英文文件還有貼心的中文 README 。
bin/touchme.js
如下
#!/usr/bin/env node const program = require('commander'); const gen = require('../lib/generate-file'); program // 版本資訊 .version('0.0.4', '-v, --version') // 用法說明 .usage('<file ...> [options]') // 選擇名 選項描述 預設值 // 選項 可以帶有一個引數 可以通過 program.copy 獲取該選項資訊 // 如果沒有引數 該值為 true .option('-c, --copy <source>', 'copy file and add comment') .option('-H, --hashtag', `comment by '#'`) .option('-s, --slash', `comment by '/'`) .parse(process.argv); function resolve(program) { // 沒有匹配任何選項的引數會被放到陣列 args 中 const { copy, hashtag, slash, args } = program; if (!args.length) { console.log('Please input filename.'); return; } if (copy === true) { console.log('You should copy at least one file.'); return; } let type = 'star'; if (slash) type = 'slash'; if (hashtag) type = 'hashtag'; for (let i = 0; i < args.length; i++) { gen(args[i], copy, type); } } resolve(program);
具體 lib/generate-file.js 實現見 https://github.com/G-lory/create-file-cli/ 就是簡單的建立一個檔案並寫入註釋。
通過 option 定義命令選項並可定義引數。
通過 program 可以獲取命令列輸入的引數資訊。
現在功能寫完了,剩下的事情就是釋出了。首先要到 https://www.npmjs.com 查詢一下自己的包名有沒有人已經發布了,如果有的話,你需要先修改包名。然後在 https://www.npmjs.com 註冊一個賬號。記住自己的賬號密碼和郵箱後,回到命令列。
$ npm login Username: ... Password: Email: (this IS public) Logged in as ... on https://registry.npmjs.org/.
注意登入成功後顯示的是 https://registry.npmjs.org/ 很多同學設定了淘寶的映象,顯示的就不是這個地址,那麼釋出之前要改回來。
$ npm config set registry=http://registry.npmjs.org
然後就可以釋出包了。
$ npm publish
如果之後有修改,更改一下 package.json
中的版本號 然後再次執行 npm publish
即可。
釋出後可以去 npm 網站搜尋一下自己的包。然後就是安裝測試一下功能。
全域性安裝一下
$ npm install create-file-cli -g
然後就可以使用 touchme
命令建立檔案了。也可以使用 touchme -h
來檢視幫助。
一個命令列工具就建立成功啦~~