1.首先搭建vue3.0项目 (默认3.0项目就行)
![](https://img.haomeiwen.com/i23538506/25625a31ab23b053.png)
项目创建之后可以看到当前目录原始结构
如下
![](https://img.haomeiwen.com/i23538506/3c1f1ddb49fded80.png)
进入项目 进行启动 看项目搭建是否成功
2.由于我们搭建的是组件库项目所以与其他项目便于区分 把我们的src 修改为 examples
此时再次启动项目会报错 (由于是修改了项目的原始路径)
所以我们要在根目录新增vue.config.js 进行配置
const path = require('path')
const join = path.join
function resolve(dir) {
return path.resolve(__dirname, dir)
}
module.exports = {
pages: {
index: {
entry: 'examples/main.js', // 修改 运行入口
template: 'public/index.html',
filename: 'index.html'
}
},
}
再次运行启动命令 项目成功跑起
另注意:
![](https://img.haomeiwen.com/i23538506/21b133c179d54d6f.png)
-
新建组件存放文件夹 packages (文件夹下包含组件 以及出口文件)
image.png
packages/index.js
// 导入button组件
import XLButton from './button'
// 组件列表
const components = [
XLButton
]
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,那么所有的组件都会被注册
const install = function (Vue) {
// 判断是否安装
if (install.installed) return
// 遍历注册全局组件
components.map(component => Vue.component(component.name, component))
}
// 判断是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
// 导出的对象必须具有 install,才能被 Vue.use() 方法安装
install,
// 以下是具体的组件列表
XLButton
}
button/src/index.vue
<template>
<div class="xl-button" @click="()=>{console.log('0000')}">
按钮
</div>
</template>
<script>
export default {
name: 'xl-button',
props: {
type: String
}
}
</script>
<style scoped>
.xl-button {
display: inline-block;
padding: 3px 6px;
background: #000;
color: #fff;
}
</style>
button/index.js
// 导入组件,组件必须声明 name
import XLButton from './src'
// 为组件提供 install 安装方法,供按需引入
XLButton.install = function (Vue) {
Vue.component(XLButton.name, XLButton)
}
// 导出组件
export default XLButton
4.再项目中引用packages 中的组件测试是否定义成功
再main.js中全局注册
![](https://img.haomeiwen.com/i23538506/c36837819e8100cc.png)
使用组件
![](https://img.haomeiwen.com/i23538506/39aa53d918ff217b.png)
再次运行项目看是否调用成功
5.对组件进行 打包压缩然后通过 node_modules 包进行调用
1、再package.json 中配置打包命令
![](https://img.haomeiwen.com/i23538506/29fb24a7f043239f.png)
新增命令
"lib": "vue-cli-service build --target lib packages/index.js --name index --dest xlui "
打包命令解释:
–target lib 关键字 指定打包的目录 也就是 packages/index.js 作为打包的入口
–name 打包后的文件名字 index
–dest 打包后的文件夹的名称 xlui
运行 npm run lib 后 文件目录新增 xlui 如下
![](https://img.haomeiwen.com/i23538506/198dc246ff5a2ad9.png)
2、把打包后的 xlui 文件整体 复制到 node_modules 下
3、在main.js中引用注册 使用同上
![](https://img.haomeiwen.com/i23538506/4f5fb47447e632c8.png)
再其他项目中使用组件库时 只需把 打包后的组件包进行复制 到所以使用组件库的项目 node_modules 下 通过main.js 全局注册 即可使用(vue2.0 vue3.0 引用语法可能不一样 稍加注意即可)
6.通过npm 账号上传的 npm 库 后续通过npm 命令 即可远程下载使用(后续测试)
网友评论