本文基於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