如何用vue工程发布单个组件

309 阅读1分钟

1. 新建工程与组件

用vue-cli搭建一个基础工程,然后新建一个组件,例如一个Banner组件:

src/components/alee-banner/AleeBanner.vue:

 <template>
   <div class="banner" :style="bannerStyles" :class="`banner__${position}`">
     <slot></slot>
   </div>
 </template>
 <script>
 const defaultStyles = {
   left: 0,
   right: 0
 };
 export default {
   name: 'AleeBanner',
   props: {
     position: {
       type: String,
       default: 'top',
       validator (position) {
         return ['top', 'bottom'].indexOf(position) > -1;
       }
     },
     styles: {
       type: Object,
       default: () => ({})
     }
   },
   data () {
     return {
       bannerStyles: {
         ...defaultStyles,
         ...this.styles
       }
     };
   }
 };
 </script>
 <style lang="less" scoped>
 .banner {
   padding: 12px;
   background-color: #fcf6cd;
   color: #f6a623;
   text-align: left;
   position: fixed;
   z-index: 2;
 }
 .banner__top {
   top: 0;
 }
 .banner__bottom {
   bottom: 0;
 }
 </style>
 ​

然后在其他组件中引用测试下:

 <alee-banner position="bottom">This is a banner!</alee-banner>

image-20210712235532066

组件可以正常使用。

2. 组件入口文件

在组件同层级下建一个index.js在全局注册组件:

 import Vue from 'vue';
 import AleeBanner from './AleeBanner.vue';
 ​
 Vue.component(AleeBanner.name, AleeBanner);
 export default AleeBanner;

3. 用不用install?

其实上面的步骤就已经注册了组件,引入后就可以直接使用。但是按照官方规范开发插件应该暴露一个install方法,这是为了传参扩展方法等。

image-20210808223838131

之后引入组件就需要再调用Vue.use方法:

 // 调用 `MyPlugin.install(Vue)`
 Vue.use(MyPlugin)
 ​
 new Vue({
   // ...组件选项
 })

因此我们上面的index.js需要改造下:

 import AleeBanner from './AleeBanner.vue';
 ​
 AleeBanner.install = Vue => Vue.component(AleeBanner.name, AleeBanner);
 ​
 export default AleeBanner;

4. 打包

修改package.json文件,添加一个lib命令打包组件:

   "scripts": {
     "serve": "vue-cli-service serve",
     "build": "vue-cli-service build",
     "lint": "vue-cli-service lint",
     "lib": "vue-cli-service build --target lib --name AleeBanner --dest lib ./src/components/alee-banner/index.js"
   },

执行npm lib:

image-20210808224733096

common.js是给打包器使用的,umd.js是给浏览器环境直接使用,demo.html中就引用了AleeBanner.umd.js可以直接打开看是否能正常打印组件信息。

5. 发布

首先需要在npm官网进行注册等就不多说了,发布前有用淘宝镜像的从淘宝镜像恢复到官方地址。

几个关键的package.json的配置需要改下:

   "main": "lib/AleeBanner.common.js",
   "name": "alee-banner",
   "version": "0.1.1",
   "files": [
     "lib/*",
     "src/*",
     "public/*",
     "*.json",
     "*.js"
   ]

然后进行npm publish,就可以成功发布了:

image-20210808231221527

在另一个工程中安装引用测试即可。

6. 总结

这只是单个组件的简单发布,利用官方脚手架快速打包发布,如果是组件库的发布还需要再做些工作,下次再详细写下。