1 介紹
以編寫Vue日誌外掛程式為例,講述從外掛程式的開發到部署。
原文 https://lluvio.github.io/blog/plugin-for-vuejs.html
2 代碼初始
不用一步到位開發外掛程式,先拋開 Vue保證自己的代碼能夠運行
var logger = { debug: false, prefix: 'Yunhuni:'}let levels = ['log', 'info', 'warn']for (let level of levels) { logger[level] = function() { if (!this.debug) return; if (typeof console == "undefined") return; var slice = Array.prototype.slice; var args = slice.call(arguments, 0); args.unshift(this.prefix + level); console[level].apply(console, args); }}logger.log('aaaa')logger.info('aaaa')logger.warn('aaaa') 3 編寫成Vue的外掛程式
上面代碼能跑了,然後再根據 文檔 接入我們的代碼
const vLogger = {}vLogger.install = function (Vue, options) { if (vLogger.installed) return var logger = { dev: true, prefix: '', levels: ['log', 'warn', 'debug'] } if (options) { for (const key of Object.keys(options)) { if (key === 'levels') { logger[key] = logger[key].concat(options[key]) } else { logger[key] = options[key] } } } for (const level of logger.levels) { logger[level] = function () { if (!this.dev || typeof console === 'undefined') return var args = Array.from(arguments) args.unshift(`[${this.prefix} :: ${level}]`.toUpperCase()) console[level].apply(console, args) } } Vue.prototype.$log = logger Vue.log = logger}export default vLogger 4 使用
import vueLogger from './logger'Vue.use(vueLogger, { prefix: new Date(), dev: true })// @test.vuethis.$log.log('hello vue log') // => [MON DEC 05 2016 15:35:00 GMT+0800 (CST) :: LOG] hello world 4.1 參數 name type default prefix string none dev boolean true levels array ['log', 'warn', 'default'] 5 編寫測試案例
使用jasmine,這裡以測試參數 options 為例子
// 測試 參數 levelimport Vue from 'vue'import Logger from '../../src/index.js'describe("this.$log", function() { Vue.use(Logger) const vm = new Vue() const str = 'hello world' it("level log out hello world", function() { expect(vm.$log.log).toBeDefined() vm.$log.log = jasmine.createSpy('log') vm.$log.log(str) expect(vm.$log.log).toHaveBeenCalledWith(str); }); it("level debug out hello world", function() { expect(vm.$log.debug).toBeDefined() vm.$log.debug = jasmine.createSpy('debug') vm.$log.debug(str) expect(vm.$log.debug).toHaveBeenCalledWith(str); }); describe("Vue log", function() { it("level debug out hello world", function() { expect(vm.$log.debug).toBeDefined() Vue.log.debug = jasmine.createSpy('debug') Vue.log.debug(str) expect(Vue.log.debug).toHaveBeenCalledWith(str); }); });}); 6 部署 6.1 如何選擇開源許可證
參考阮老師的 文章 6.2 添加項目徽章
通過這些微章簡單直白的瞭解該項目的狀態。 可以在這個 網站 擷取你想要svg,一般格式如下

想要表徵圖點擊可跳轉
[](https://circleci.com/gh/Lluvio/vue-logger)
7 發布
首先需要在本地添加 npm 使用者
# 帳號密碼和你在 npm 官網註冊的帳號一致npm adduser# 然後登入npm login
如果想要指定特定標籤,參考 這裡 7.1 publish 失敗
出現以下錯誤,有可能是Proxy 位址錯誤,每個命令後都需要帶上 --registry http://registry.npmjs.org
no_perms Private mode enable, only admin can publish this module
8 最後
最終結果在 這裡 , 歡迎指正!