写此文前特地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不是轮子),一个属于本身轮子,在造轮子的工程中你能学到不少不少,没错,接下来我可能,,,哼哼