前言
如果你想寫一個npm插件,如果你想通過命令行來簡化自己的操作,如果你也是個懶惰的人,那么這篇文章值得一看。
po主的上一篇文章介紹了定制自己的模版,但這樣po主還是不滿足啊,項目中我們頻繁的需要新建一些頁面,邏輯樣式等文件,每次都手動new一個,然后復制一些基本代碼進去非常的麻煩,所以就有了這篇文章。接下來就讓po主為大家一步一步演示怎么做一個npm命令行插件。
注冊npm賬戶
發布npm插件,首先肯定要有個npm帳號了,過程就不啰嗦了,走你。
有了賬號后,我們通過npm init 生成一個package配置文件,填寫一些你的信息,然后就可以開始寫邏輯代碼了。
編寫命令入口
首先看一下項目結構
.
├── bin //命令配置
├── README.md //說明文檔
├── index.js //主入口
├── src //功能文件
├── package.json //包信息
└── test //測試用例
實例命令代碼都是寫在bin目錄下,我們現在配置文件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可以在系統的PATH目錄中查找。同時,env還規定一些系統環境變量。 這種寫法主要是為了讓你的程序在不同的系統上都能適用。
在這一步,你可以簡單測試你自己的npm插件
$ node ./bin/xu.js
>>> 輸出一些插件usage。help信息
關於commander,大家可以去作者的Github先學習了解,這里不對參數講解。
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);
});返回一個函數,這個函數就是我們定義這個命令需要做什么事。
編寫功能函數
./src/generate.js
這個文件就定義了當我們輸入
$ 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文件導出了一個run函數給 xu-generate.js調用,我們通過參數拿到了用戶輸入的type,name,然后就可以根據type通過node fs模塊(這里用了一個依賴,不過原理還是fs)操作把template文件復制了一份到你的項目中。
到這,我們就已經完成了一個命令的開發,這個命令可以快速生成項目的模版文件。
本地測試
npm包開發不像web開發,可以直接在瀏覽器看,實例目錄下建立一個test文件,再 node test 就可以測試我們的邏輯。如果有一些功能需要在發布后才能測,npm 有個 link命令 可以連接你本地的模塊,當然你也可以發布后 自己安裝插件測試,就跟平時引入一個插件一樣。
發布npm包
首先在項目根目錄執行npm登陸
$ npm login
$ npm publish
如果這里有個報錯,可能是你使用了cnpm地址,需要把npm倉庫設置回來
$ npm config set registry https://registry.npmjs.org/
然后,更新更新npm包,版本號需要大於上一次
后記
至此,一個入門級的npm包就制作完成了。萬分感慨,記得剛入門前端的時候看到別人的插件做的真牛,自己只要簡單安裝一下就能搞得那么漂亮,想搞~但是看到一堆陌生的東西,立刻慫了(node環境,東西非常非常多,直接拷個vue-cli看到一對代碼,一頭霧水。。。大牛請無視)
學習是一個循序漸進的過程,大牛寫出來的東西,沒有一定的基礎,和長時間的積累經驗,源碼是很難學習。非要啃,也行,只是效率感覺不如循序漸進來的好。
插件已經發布,Github也有完整源碼,想學習的同學可以fork一個自己玩玩,干這一行~隨心所動 ,跟着興趣走,准沒錯
傳送門: npm地址
傳送門: github源碼
如果覺得本文對你有所幫助,就star一下吧~大傳送之術! 我的博客Github
前端❤️~越學越感覺自己的無知哎~