十分鐘經過 NPM 建立一個命令行工具

大過年的,要不要寫點代碼壓壓驚?來花十分鐘學一下怎麼經過 NPM 構建一個命令行工具。node

寫了一個小 demo,用於代替 touch 的建立文件命令 touchme ,能夠建立自帶「佛祖保佑」註釋的文件。效果以下: git

命令能夠帶有一個參數,選擇註釋的符號github

如今,開始擼代碼 ~web

首先建立一個文件夾,我起名字 create-file-cli 而後經過 npm init 命令建立 package.json 文件。npm

$ mkdir create-file-cli
$ cd create-file-cli
$ npm init -y

而後修改 package.json 添加一個 bin 字段,定義一個 touchme 命令,並指定該命令執行的文件。json

{
  "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 來查看幫助。

一個命令行工具就建立成功啦~~

相關文章
相關標籤/搜索