咱们在作项目的时候,一般会须要一些公用的基础组件,好比dialog、alert、form、table等等,大多数状况下如今的开源组件库已经能知足咱们的须要了,好比基于vue的element-ui、vant、iview等等。可是总会有一些功能是开源组件库覆盖不了的,这就须要咱们本身手动去开发组件,可是这些组件有可能会被团队内多个项目用到,怎么才能在多个项目中共享这些组件,这里就须要咱们搭建本身的组件库,接下来我就讲讲本身的实践。css
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(单独文件),你们可根据本身的使用习惯自行选择。html
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.vuewebpack
<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.jsgit
import test from './src/test'; export default Vue => { Vue.component(test.name, test); };
package/index.jsgithub
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.jsonweb
// 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