咱們在作項目的時候,一般會須要一些公用的基礎組件,好比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