封裝vue元件庫,釋出到npm
封裝vue元件庫
元件庫的開發和平時專案中元件的開發過程是一樣的,不同的是元件庫作為一個外掛使用,使用Vue.use()
註冊外掛。
Vue.use
方法可以接收一個函式,如果是函式會直接呼叫這個函式;可以傳入物件,傳入物件,會呼叫這個物件的install
方法。
vue
規定外掛應該暴露一個install
方法。這個方法的第一個引數是Vue
構造器,第二個引數是一個可選的選項物件。
如果是直接引入元件庫(如:上傳cnd
引入),那麼需要在封裝元件庫時判斷是否是window
,並且window
有Vue
,就install(window.Vue)
元件開發
在根目錄下新建一個packages
資料夾存放所有的元件,在packages
button
資料夾,下面新建一個main.vue
和index.js
main.vue
檔案變形元件相關的業務,和平時專案中開發的元件一樣
<template> <button class="yun-button" :class="[`yun-button--${type}`,{ 'is-plain': plain, 'is-round': round, 'is-circle': circle, 'is-disabled': disabled }]" :disabled="disabled" @click="handleClick"> <i v-if="icon" :class="icon"></i> <span v-if="$slots.default"><slot></slot></span> </button> </template> <script> export default { name: 'YunButton', props: { type: { type: String, default: 'default' }, plain: { type: Boolean, default: false }, round: { type: Boolean, default: false }, circle: { type: Boolean, default: false }, icon: { type: String, default: '' }, disabled: { type: Boolean, default: false } }, methods: { handleClick (e) { this.$emit('click', e) } } } </script>
index.js
檔案中主要是編寫一個install
,供按需引入
// 匯入元件,元件必須宣告 name
import YunButton from './src/button'
YunButton.install = function (Vue) {
// 為元件提供 install 安裝方法,供按需引入
Vue.component(YunButton.name, YunButton)
}
export default YunButton
到這裡我們的button
元件已經封裝好了,回到packages
目錄新建一個index.js
檔案,該檔案作為整個元件庫的入口,在該檔案中引入所有的元件,遍歷元件新增install
import MyButton from './button'
const components = [MyButton]
// 定義 install 方法,接收 Vue 作為引數。如果使用 use 註冊外掛,則所有的元件都將被註冊
const install = function (Vue) {
// 遍歷註冊全域性元件
components.forEach(component => {
Vue.component(component.name, component)
})
}
// 判斷是否直接引入檔案(通過連線引入元件庫),如果是,就不用呼叫 Vue.use()
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
// 匯出的物件必須具有 install,才能被 Vue.use() 方法安裝
install,
// 以下是具體的元件列表
MyButton
}
到這裡元件庫已經封裝完畢,只需要引入專案就可以使用了
在專案的main.js
中引入並且使用Vue.use()
註冊
import MyUi from '../packages'
Vue.use(MyUi)
元件庫打包釋出npm
vue-cli 構建目標為庫的介紹
根目錄新增vue.config.js
檔案修改打包配置
const path = require('path')
module.exports = {
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
}
},
// 擴充套件 webpack 配置,使 packages 加入編譯
chainWebpack: config => {
config.module
.rule('js')
.include.add(path.resolve(__dirname, 'packages')).end()
.use('babel')
.loader('babel-loader')
.tap(options => {
// 修改它的選項....
return options
})
}
}
在package.json
新增打包命令把packages
打包"lib": "vue-cli-service build --target lib packages/index.js"
程式碼上傳GitHub
託管
修改package.json:private
屬性值改為 false,私有包npm
不讓上傳;name
屬性值要npm
上沒有的;新增main
屬性,值為入口檔案路徑,該屬性是一定要指定的(如:"main": "dist/myui.umd.min.js"
),將來匯入到專案將會預設匯入該檔案
根目錄新增.npmignore
檔案,用於配置忽略檔案不被npm
上傳
上傳npm
:源需要是npm
,不能是淘寶源;npm login
登入(需要先註冊賬號);npm publish
釋出
以後修改後再上傳需要修改package.json
中的version
屬性,否則上傳不了