vue封装第三方插件并发布到npm的方法

前言

写此文前特意google了一下,因为有较详细的开发教程我再写意义不大,有把插件封装成组件的教程,有把自己的组件封住成插件的教程,本文主要说明如何把第三方的插件封装成vue插件,简化配置,一键安装,主要提供思路,封装方法大同小异·,文章略长要有耐心。

gitment

gitment是一个基于github issues封装的评论插件,以这个插件作为演示,把它封装成vue插件。vue-gitment,该插件已发布到npm,并在自己的开源项目vueblog中安装使用

项目初始化

封装vue的插件用webpack-simple很合适,vue init webpack-simple vue-gitment此命令创建我们的项目的目录,创建文件夹和文件,最后结构是这样的

lib目录是我们的插件目录,其他的默认就好

修改配置项

首先是修改package.json

{
 "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.json

修改webpack.config.js

我们只需配置入口和出口,不要删除默认的配置,因为后面开发好插件,我们需要查看工作效果

修改index.html

因为我们修改了webpack配置,自然要把script的src修改一下

封装插件

VueComment.vue内容如下

<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>

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6168.html