vue封装第三方插件并发布到npm的方法(2)
相信熟悉vue的一眼都看懂了,render函数是gitment对象的方法,不用关心,和我们开发组件是一样一样的
index.js封装组件
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一个插件了,简单吧
测试插件
首先测试build是否成功
npm run builddist目录会生成如下文件

可喜可贺,接下来测试插件是否正常工作
我们需要把package和webpack的修改一下,这就是为什么我前面说不要删除而是注释掉 ,把package.json的main修改为dist/build.js,wepack的entry和filename换成默认配置,index.html的src也换成默认的
在main.js中引入我们的组件
import VueComment from './lib/index.js' Vue.use(VueComment)
App.vue中使用我们的插件
<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不是轮子),一个属于自己轮子,在造轮子的工程中你能学到很多很多
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
