寫此文前特地google了一下,由於有較詳細的開發教程我再寫意義不大,有把插件封裝成組件的教程,有把本身的組件封住成插件的教程,本文主要說明如何把第三方的插件封裝成vue插件,簡化配置,一鍵安裝,主要提供思路,封裝方法大同小異·,文章略長要有耐心。css
gitment是一個基於github issues封裝的評論插件,以這個插件做爲演示,把它封裝成vue插件。vue-gitment,該插件已發佈到npm,並在本身的開源項目Essays中安裝使用html
封裝vue的插件用webpack-simple很合適,vue init webpack-simple vue-gitment
此命令建立咱們的項目的目錄,建立文件夾和文件,最後結構是這樣的
前端
lib目錄是咱們的插件目錄,其餘的默認就好vue
{
"name": "vue-gitment",
"version": "0.1.1",
"description": "A comment plugin by gitment",
"main": "dist/vue-gitment.js",
"directories": {
"dist": "dist"
},
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vue-blog/vue-gitment.git"
},
"dependencies": {
"gitment": "^0.0.3",
"vue": "^2.3.3"
},
"devDependencies": {
},
"author": "wmui",
"license": "MIT",
"bugs": {
"url": "https://github.com/vue-blog/vue-gitment/issues"
},
"homepage": "https://github.com/vue-blog/vue-gitment#readme"
}
複製代碼
把依賴性gitment添加到dependencies,main是咱們打包後的文件入口,你能夠用npm init命令生成一個package.jsonwebpack
咱們只需配置入口和出口,不要刪除默認的配置,由於後面開發好插件,咱們須要查看工做效果git
<template>
<div v-comment="options"></div>
</template>
<script>
// 引入依賴項
import Gitment from 'gitment'
export default {
name: 'vue-comment',
props: ['options'],
directives: {
// 自定義指令
comment: {
bind: function (el, binding) {
const gitment = new Gitment({
id: binding.value.id + '',
owner: binding.value.owner,
repo: binding.value.repo,
oauth: {
client_id: binding.value.oauth.client_id,
client_secret: binding.value.oauth.client_secret
}
})
gitment.render(el)
}
}
}
}
</script>
複製代碼
相信熟悉vue的一眼都看懂了,render函數是gitment對象的方法,不用關心,和咱們開發組件是同樣同樣的
index.js封裝組件github
import VueComment from './VueComment.vue'
const comment = {
install: function(Vue) {
Vue.component(VueComment.name, VueComment)
}
}
// 這裏的判斷很重要
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(comment)
}
export default comment
複製代碼
咱們在webpack配置的入口文件就是他,install是掛載組件的方法,有了它咱們就能夠在外部use一個插件了,簡單吧web
首先測試build是否成功
npm run build
dist目錄會生成以下文件
npm
import VueComment from './lib/index.js'
Vue.use(VueComment)
複製代碼
App.vue中使用咱們的插件json
<template>
<div id="app">
<vue-comment :options="options" v-if="options"></vue-comment>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
options: {
id: 'article id',
owner: 'Your GitHub ID',
repo: 'The repo to store comments',
oauth: {
client_id: 'Your client ID',
client_secret: 'Your client secret',
}
}
}
}
}
</script>
<style>
@import '~gitment/style/default.css';
</style>
複製代碼
執行npm run dev
Error: Not Found
是由於我沒配置client_id。
完成測試工做後咱們就能夠發佈到npm了,這個就比較見到了,註冊個npm帳號,在你要發佈的項目目錄執行npm login
,輸入帳號密碼和郵箱,而後npm publish
就發佈成功了,npm install vue-gitment
查看效果,建議直接看源代碼,由於真的很簡單。
本身動手豐衣足食,我以爲每一個前端開發者都要一個屬於本身的輪子(雖然vue-gitment不是輪子),一個屬於本身輪子,在造輪子的工程中你能學到不少不少,沒錯,接下來我可能,,,哼哼