脚本宝典收集整理的这篇文章主要介绍了基于@vue/cli 3搭建属于自己的组件库(1),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我们在做项目的时候,通常会需要一些公用的基础组件,比如dialog、alert、form、table等等,大多数情况下现在的开源组件库已经能满足我们的需要了,比如基于vue的element-ui、vant、iview等等。但是总会有一些功能是开源组件库覆盖不了的,这就需要我们自己手动去开发组件,但是这些组件有可能会被团队内多个项目用到,怎么才能在多个项目中共享这些组件,这里就需要我们搭建自己的组件库,接下来我就讲讲自己的实践。
vue create xxx-ui
default (babel, eslint)
> Manually select features
? Check the features needed for your project: (*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
>(*) Vuex
(*) CSS Pre-processors
(*) Linter / Formatter
(*) Unit Testing
( ) E2E Testing
router选择hash,CSS Pre-processors选择sass/scss,lint选择ESLint + Prettier,unit test选择Mocha + Chai,配置文件选择In dedicated config files(单独文件),大家可根据自己的使用习惯自行选择。
module.exports = {
// 修改默认的入口
pages: {
index: {
entry: 'examples/main.js',
template: 'public/index.html',
filename: 'index.html'
}
},
chainWebpack: config => {
// vue默认@指向src目录,这里要修正为examples,另外新增一个~指向packages
config.resolve.alias
.set('@', path.resolve('examples'))
.set('~', path.resolve('packages'));
// lib目录是组件库最终打包好存放的地方,不需要eslint检查
// examples/docs是存放md文档的地方,也不需要eslint检查
config.module
.rule('eslint')
.exclude.add(path.resolve('lib'))
.end()
.exclude.add(path.resolve('examples/docs'))
.end();
// packages和examples目录需要加入编译
config.module
.rule('js')
.include.add(/packages/)
.end()
.include.add(/examples/)
.end()
.use('babel')
.loader('babel-loader')
.tap(options => {
// 修改它的选项...
return options;
});
}
};
test.vue
<template>
<div>
<h3>{{name}}</h3>
<div class="num">{{ count }}</div>
<button @click="increment">自增</button>
</div>
</template>
<script>
export default {
name: 'test',
props: {
name: String,
default: ''
},
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
};
</script>
packages/test/index.js
import test from './src/test';
export default Vue => {
Vue.component(test.name, test);
};
package/index.js
import test from './test';
const components = [test];
const install = function(Vue) {
if (install.installed) return;
components.map(component => {
Vue.use(component);
});
};
// 全局引用可自动安装
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default {
install,
test
};
export { test };
package.json
// npm输出的文件
main: "lib/xxx-ui.common.js",
// 新增命令
scripts: {
"lib": "vue-cli-service build --target lib --name xxx-ui --dest lib packages/index.js"
}
npm run lib
npm publish
我们就发布了自己的组件库,但是一个完整的组件库还包含文档、单元测试、按需加载等功能,这些我会在后续的文章中将我的实践列出来如有不足之处,还望大家指出
以上是脚本宝典为你收集整理的基于@vue/cli 3搭建属于自己的组件库(1)全部内容,希望文章能够帮你解决基于@vue/cli 3搭建属于自己的组件库(1)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。