通過npm寫一個cli命令行工具

前言

如果你想寫一個npm插件,如果你想通過命令行來簡化自己的操作,如果你也是個懶惰的人,那么這篇文章值得一看。

po主的上一篇文章介紹了定制自己的模版,但這樣po主還是不滿足啊,項目中我們頻繁的需要新建一些頁面,邏輯樣式等文件,每次都手動new一個,然后復(fù)制一些基本代碼進去非常的麻煩,所以就有了這篇文章。接下來就讓po主為大家一步一步演示怎么做一個npm命令行插件。

實例插件

注冊npm賬戶

發(fā)布npm插件,首先肯定要有個npm帳號了,過程就不啰嗦了,走你。

npm官網(wǎng)

有了賬號后,我們通過npm init 生成一個package配置文件,填寫一些你的信息,然后就可以開始寫邏輯代碼了。

編寫命令入口

首先看一下項目結(jié)構(gòu)

.
├── bin           //命令配置
├── README.md     //說明文檔
├── index.js      //主入口
├── src           //功能文件
├── package.json  //包信息
└── test          //測試用例

實例命令代碼都是寫在bin目錄下,我們現(xiàn)在配置文件package文件中啟用命令,添加一個配置項bin

 "bin": {
        "xu": "./bin/xu.js"
    },

然后安裝一個依賴,TJ大神寫的commander插件,

npm i commander --save

有了這個工具我們可以很方便的編寫命令代碼

xu.js

#!/usr/bin/env node

process.title = 'xu';

require('commander')
.version(require('../package').version)
.usage('<command> [options]')
.command('generate', 'generate file from a template (short-cut alias: "g")')
.parse(process.argv)


require('./xu-generate');   >>引入

這個文件可以看作是入口文件,第一行代碼是必須添加的,腳本用env啟動的原因,是因為腳本解釋器在linux中可能被安裝于不同的目錄,env可以在系統(tǒng)的PATH目錄中查找。同時,env還規(guī)定一些系統(tǒng)環(huán)境變量。 這種寫法主要是為了讓你的程序在不同的系統(tǒng)上都能適用。

在這一步,你可以簡單測試你自己的npm插件

$ node ./bin/xu.js

>>>  輸出一些插件usage。help信息

關(guān)于commander,大家可以去作者的Github先學(xué)習(xí)了解,這里不對參數(shù)講解。

xu-generate.js

#!/usr/bin/env node

const program = require('commander');
const chalk = require('chalk')
const xu = require('../src/generate');


/**
 * Usage.
 */

program
.command('generate')
.description('quick generate your file')
.alias('g')
.action(function(type, name){
    xu.run(type, name);
});
program.parse(process.argv);

這就是功能命令,定義了一個generate命令,.alias('g')是該命令的縮寫,然后.action(function(type, name){
xu.run(type, name);
});返回一個函數(shù),這個函數(shù)就是我們定義這個命令需要做什么事。

編寫功能函數(shù)

./src/generate.js

這個文件就定義了當(dāng)我們輸入

$ xu g

所做的操作了。

/**
 * Created by xushaoping on 17/10/11.
 */

const fs = require('fs-extra')
const chalk = require('chalk')
exports.run = function(type, name) {
    switch (type) {
        case 'page':
            const pageFile = './src/page/' + name + '/' + name + '.vue'
            const styleFile = './src/page/' + name + '/' + name + '.less'
            fs.pathExists(pageFile, (err, exists) => {
                if (exists) {
                    console.log('this file has created')
                } else {
                    fs.copy('/usr/local/lib/node_modules/vue-xu-generate/src/template/page.vue', pageFile, err => {
                        if (err) return console.error(err)
                
                        console.log(pageFile + '  has created')
                    })
                    fs.copy('/usr/local/lib/node_modules/vue-xu-generate/src/template/page.less', styleFile, err => {
                        if (err) return console.error(err)
                
                        console.log(styleFile + '  has created')
                    })
                }
            })
            break;
        case 'component':
            const componentFile = './src/components/' + name + '.vue'
            fs.pathExists(componentFile, (err, exists) => {
                if (exists) {
                    console.log('this file has created')
                } else {
                    fs.copy('/usr/local/lib/node_modules/vue-xu-generate/src/template/component.vue', componentFile, err => {
                        if (err) return console.error(err)
                    
                        console.log(componentFile + '  has created')
                    })
                }
            })
            break;
        case 'store':
            const storeFile = './src/store/modules' + name + '.js'
            fs.pathExists(storeFile, (err, exists) => {
                if (exists) {
                    console.log('this file has created')
                } else {
                    fs.copy('/usr/local/lib/node_modules/vue-xu-generate/src/template/store.js', storeFile, err => {
                        if (err) return console.error(err)
                    
                        console.log(storeFile + '  has created')
                    })
                }
            })
            break;
        default:
            console.log(chalk.red(`ERROR: uncaught type , you should input like $ xu g page demo` ))
            console.log()
            console.log('  Examples:')
            console.log()
            console.log(chalk.gray('    # create a new page'))
            console.log('    $ xu g page product')
            console.log()
            console.log(chalk.gray('    # create a new component'))
            console.log('    $ xu g component  product')
            console.log()
            console.log(chalk.gray('    # create a new store'))
            console.log('    $ xu g store  product')
            console.log()
            break;
    }
};


這里有2個新的依賴,分別是命令輸出顏色和一個文件操作的插件,通過npm安裝。

$ npm i fs-extra --save

$ npm i chalk --save

這個js文件導(dǎo)出了一個run函數(shù)給 xu-generate.js調(diào)用,我們通過參數(shù)拿到了用戶輸入的type,name,然后就可以根據(jù)type通過node fs模塊(這里用了一個依賴,不過原理還是fs)操作把template文件復(fù)制了一份到你的項目中。

到這,我們就已經(jīng)完成了一個命令的開發(fā),這個命令可以快速生成項目的模版文件。

本地測試

npm包開發(fā)不像web開發(fā),可以直接在瀏覽器看,實例目錄下建立一個test文件,再 node test 就可以測試我們的邏輯。如果有一些功能需要在發(fā)布后才能測,npm 有個 link命令 可以連接你本地的模塊,當(dāng)然你也可以發(fā)布后 自己安裝插件測試,就跟平時引入一個插件一樣。

發(fā)布npm包

首先在項目根目錄執(zhí)行npm登陸

$ npm login 

$ npm publish

如果這里有個報錯,可能是你使用了cnpm地址,需要把npm倉庫設(shè)置回來

 $ npm config set registry https://registry.npmjs.org/

然后,更新更新npm包,版本號需要大于上一次

后記

至此,一個入門級的npm包就制作完成了。萬分感慨,記得剛?cè)腴T前端的時候看到別人的插件做的真牛,自己只要簡單安裝一下就能搞得那么漂亮,想搞~但是看到一堆陌生的東西,立刻慫了(node環(huán)境,東西非常非常多,直接拷個vue-cli看到一對代碼,一頭霧水。。。大牛請無視)

學(xué)習(xí)是一個循序漸進的過程,大牛寫出來的東西,沒有一定的基礎(chǔ),和長時間的積累經(jīng)驗,源碼是很難學(xué)習(xí)。非要啃,也行,只是效率感覺不如循序漸進來的好。

插件已經(jīng)發(fā)布,Github也有完整源碼,想學(xué)習(xí)的同學(xué)可以fork一個自己玩玩,干這一行~隨心所動 ,跟著興趣走,準(zhǔn)沒錯

傳送門: npm地址

傳送門: github源碼

如果覺得本文對你有所幫助,就star一下吧~大傳送之術(shù)! 我的博客Github

前端??~越學(xué)越感覺自己的無知哎~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,953評論 6 342
  • 無意中看到zhangwnag大佬分享的webpack教程感覺受益匪淺,特此分享以備自己日后查看,也希望更多的人看到...
    小小字符閱讀 8,227評論 7 35
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,284評論 25 708
  • GitChat技術(shù)雜談 前言 本文較長,為了節(jié)省你的閱讀時間,在文前列寫作思路如下: 什么是 webpack,它要...
    蕭玄辭閱讀 12,715評論 7 110
  • 敬篤 一 一個靈魂的哨兵,在機場為我們探視黎明。他看到了來自布魯塞爾的秋天,即將穿越時空來到昆明,因為這里有手持蘭...
    山谷小道士閱讀 569評論 0 5