封装了几个Vue组件,怎么把它们制作制作成插件呢

先新建Vue项目

1
vue create my-ui

在my-ui文件夹中新建packages和examples文件夹,packages用来存放我们封装的所有组件,examples用来进行测试,把src改成examples

新建vue.config.js,写入如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const path = require('path')
module.exports = {
pages: {
index: {
entry: 'examples/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
})
}
}

将封装好的vue组件全部放到packages文件夹中,同时也要打包字体图标文件,将fonts文件夹也放到packages文件夹中

这里需要了解Vue的install方法,见Vue官方文档Vue.use(plugin),意思是想要做一个插件,插件只要导出一个install就行,在packages文件夹中新建index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 整个包的入口
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件搜将被注册
// 导入颜色选择器组件
import ColorPicker from './color-picker'
import Button from './button'
import Dialog from './dialog'
import Input from './input'
import Checkbox from './checkbox'
import Radio from './radio'
import Switch from './switch'
import './fonts/font.scss'
// 存储组件列表
const components = [
ColorPicker,
Button,
Dialog,
Input,
Checkbox,
Radio,
Switch
]
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件都将被注册
const install = function (Vue) {
// 遍历注册全局组件
components.forEach(component => {
Vue.component(component.name, component)
})
}
// 判断是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
// 导出的对象必须具有 install,才能被 Vue.use() 方法安装
install,
// 以下是具体的组件列表
ColorPicker,
Button,
Dialog,
Input,
Checkbox,
Radio,
Switch
}

在examples的main.js中输入

1
2
3
4
5
6
7
8
9
10
11
12
import Vue from 'vue'
// 导入组件库
import HmUI from './../packages'
import App from './App.vue'

Vue.use(HmUI)

Vue.config.productionTip = false

new Vue({
render: h => h(App)
}).$mount('#app')

这时就可以使用了,在examples中测试一下

1
2
3
4
5
<template>
<div id="app">
<hm-button type="primary">按钮</hm-button>
</div>
</template>

最后,examples文件夹是没用的,真正有用的是packages文件夹