本文基于vue3.0进行组件开发并发布。
1 初始化项目
cmd 中 vue create plugin-test 进行创建
2 组件开发
创建目录plugin用户存放组件,新建PluginTest文件用于存放PluginTest插件,文件夹中包含两个文件:
index.js
// 为组件提供 install 安装方法,供按需引入
import PluginTest from './PluginTest.vue';
PluginTest.install = Vue => Vue.component(PluginTest.name,PluginTest)
export default PluginTest
PluginTest.vue
<template>
<div>hello {{datas}}</div>
</template>
<script>
export default {
name:'PluginTest',
data() {
return {
}
},
props:{
datas:String
}
}
</script>
<style lang="scss" scoped>
</style>
3 整合所有的组件,对外导出,即一个完整的组件库
在src下创建index.js主入口
//导入组件
import pluginTest from './components/pluginTest/index';
//存在所有组件
const components = [pluginTest]
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件都将被注册
const install = function (Vue, opts = {}) {
// 判断是否安装
if (install.installed) return
// 遍历注册全局组件
components.map((component) => {
vue.component(component.name, component) //此处的使用的组件vue文件中的name属性
})
// 判断是否是直接引入文件
if (typeof window != 'undefined' && window.Vue) {
install(window.Vue)
}
}
export default {
// 导出的对象必须具有 install,才能被 Vue.use() 方法安装
install,
// 以下是具体的组件列表
pluginTest
}
4 测试组件
<template>
<div class="hello">
<PluginTest datas="Quentin"></PluginTest>
</div>
</template>
<script>
import Vue from 'vue'
//导入组件
import PluginTest from '../plugin/PluginTest/index';
//使用组件
Vue.use(PluginTest)
export default {
name: 'HelloWorld',
props: {
msg: String
},
components:{
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
如果组件能正常显示,说明组件编写成功
5 组织配置文件
在package.json中一条命令 npm run lib
vue-cli 3 的官方文档有打包库的相关配置
主要需要四个参数:
1,target: 默认为构建应用,改为 lib 即可启用构建库模式
2,name: 输出文件名
3,dest: 输出目录,默认为 dist,这里我们改为 lib
4,entry: 入口文件路径,默认为 src/App.vue,这里改为 src/index.js 此处对应的是你配置的主入口,统一注册组件的地方,第三步已进行描述。
"lib": "vue-cli-service build --target lib --name plugintest --dest lib src/index.js"
6 运行打包生成对应的插件文件
npm run lib ,会在lib下生成对应文件
7 发布插件到npm
1,注册npm账号
2,登录npm
3,进行npm publish