目标:
- 搭建一个用来开发,测试公共组件库的项目架子
通过vuecli创建项目,这个项目创建的目的有三个:
- 维护组件库(不是某个具体的业务项目哦,而是造轮子)
- 本地测试组件库
- 整体打包上传到npm
使用脚手架工具创建项目
命令:
vue create XXXXX
项目名尽量不要太大众(与别人重复),后期我们会把这个项目打包上传到npm上,如果你的名字与现有的包名重复,则无法上传。
要点:
- vue2.0 + Babel + Router + Linter/Formatter + less
? Please pick a preset: Manually select features
? Check the features needed for your project:
(*) Choose Vue version
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
( ) Vuex
>(*) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save, Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? (y/N) n
调整目录结构
由于我们这个项目是用来开发组件库的,并不是某个具体的业务,所以,要调整目录结构,方便理解。
调整明细
在项目根目录下(与src并列的位置,不是在src中)
|-packages(额外添加的) 所有的组件放在这里。
|-examples(把src重命名成这个)主要是方便我们理解。examples下的内容是来测试packages下的组件的使用
如果你已经启动了项目,可能src的重命名会不成功,此时,你需要停止项目,再去重命名。
设置vue.config.js
由于这里改了src这个目录的名字,所以还需要做一些设置。
创建vue.config.js,并设置内容如下:
const path = require('path')
module.exports = {
// 将 examples 目录添加为新的页面
pages: {
index: {
// page 的入口
entry: 'examples/main.js',
// 模板来源
template: 'public/index.html',
// 输出文件名
filename: 'index.html'
}
},
configureWebpack: {
resolve: {
alias: {
'@': path.resolve('./examples')
}
}
}
}
此时,运行项目,应该就可以成功地启动了。
创建button组件
在packages目录下建立button/button.vue。先随意添加一些内容,等我们后面再来调整。
目前,这它的内容如下。
<template>
<button type="button" class="my-button my-button--primary is-disabled">
<span>默认按钮</span>
</button>
</template>
<script>
export default {}
</script>
导出这个组件
packages整体是要做一个组件库,它会将所有定义的组件做统一导出。在packages目录下,创建index.js文件。用它来收集所有定义在packages目录下的组件,并按vue插件的格式做导出。
// 导入在packages下创建的各个组件
import Button from './button/button.vue'
// vue插件格式
const ui = {
install: function (Vue) {
console.log('install ...... ')
Vue.component('MyButton', Button)
}
}
// 导出
export default ui
注册为全局组件
在examples下的main.js目录下
import Vue from 'vue'
import App from './App.vue'
import router from './router'
// 导入封装好的vue插件,并使用
// 引入一个NB组件库
import UI from '../packages/index.js'
Vue.use(UI)
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
在其它组件中使用
在examples/views/about.vue,直接使用这个组件
<template>
<div class="about">
<h1>This is an about page</h1>
<!-- 直接使用这个按钮组件。
因为它是一个全局组件,不是about.vue的局部组件 -->
<my-button></my-button>
</div>
</template>
效果: