封装了几个Vue组件,怎么把它们制作制作成插件呢
先新建Vue项目
在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' } }, 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
|
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 ]
const install = function (Vue) { components.forEach(component => { Vue.component(component.name, component) }) }
if (typeof window !== 'undefined' && window.Vue) { install(window.Vue) } export default { 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文件夹