创建一个vue2项目
npm install -g @vue/cli
vue create xiaoququ-ui
根目录下新建一个plugins文件夹,用来放组件
vue.config.js配置打包规则
const path = require('path')
module.exports = {
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
}
},
chainWebpack: config => {
config.resolve.alias
.set('~', path.resolve('plugins'))
config.module
.rule('js')
.include.add(/plugins/).end()
.use('babel')
.loader('babel-loader')
.tap(options => {
return options
})
}
}
编写组件
- qbutton/qbutton.vue 自定义颜色按钮
<template>
<div>
<h1 class="blue">你是二憨憨</h1>
<button class="btn" :style="{ '--color': color, '--mixColor': mixColor }">按鈕</button>
</div>
</template>
<script>
export default {
name: 'qqButton',
props: {
color: {
type: String,
default: '#e83e8c'
},
},
computed: {
mixColor() {
return this.getRgbNum(this.color, 0.1)
}
},
methods: {
getRgbNum(sColor, percent) {
if (sColor.length === 4) {
let sColorNew = '#'
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
}
sColor = sColorNew
}
let sColorChange = []
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
}
return 'rgba(' + sColorChange.join(',') + ',' + percent + ')'
},
},
}
</script>
<style lang='scss' scoped>
$color: var(--color);
.btn {
padding: 20px 40px;
font-size: 30px;
color: $color;
background: var(--mixColor);
border: 1px solid $color;
border-radius: 10px;
}
</style>
import qbutton from "./qbutton.vue";
qbutton.install = Vue => Vue.component(qbutton.name, qbutton);
export default qbutton;
import qinput from "./components/qinput/qinput.vue";
import qbutton from "./components/qbutton/qbutton.vue";
const components = [qinput, qbutton];
const install = Vue => {
if (install.installed) return;
install.installed = true;
components.map(component => Vue.component(component.name, component));
};
if (typeof window !== "undefined" && window.Vue) {
install(window.Vue);
}
export default {
install,
...components
};
测试组件
import ComponentBox from "../plugins/index";
Vue.use(ComponentBox)
<template>
<div>
<qq-input></qq-input>
<qq-button color="#2e93ff"></qq-button>
<qq-button color="#ff976a"></qq-button>
<qq-button color="#ee0a24"></qq-button>
<qq-button color="#07c160"></qq-button>
<qq-button color="#ccc"></qq-button>
</div>
</template>
打包配置
{
"name": "xiaoququ-ui",
"version": "1.0.1",
"private": false,
"description": "第一个组件库",
"author": "小曲曲",
"license": "MIT",
"keywords": [
"小曲"
],
"main": "dist/xiaoququ-ui.umd.min.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lib": "vue-cli-service build --target lib --name xiaoququ-ui plugins/index.js",
"lint": "vue-cli-service lint"
},
}
发布到npm
- npm run lib 打包生成dist文件夹
- npm login 输入npm账号、密码(输不进去无所谓)、邮箱、验证码(发送邮箱)
- npm publish (发布失败检查是否包名重复)
使用组件库
- npm i xiaoququ-ui
- main.js
import ququ from "xiaoququ-ui";
import "xiaoququ-ui/dist/xiaoququ-ui.css";
Vue.use(ququ)
<qq-button color="#ccc"></qq-button>
遗留问题