vue自定义组件库发布npm

一,什么是自建组件库?

就是在公司建立自己的类似element-ui组件库,当然第三方都是些通用组件,在公司不限定,业务通用组件也可以算其中的范围。

二,为什么要有自身的组件库?

1.目前公司vue移动端的项目比较多,有一些比较通用的组件重复编写,有组件库避免重复造轮子。
2.一旦组件有什么bug,我们只需要从源头修改,降低维护成本。总而言之,目的降本增效。
3.能提升开发人员封装技能,以前只考虑自己眼前的业务,如果贡献组件库要考虑通用性,以及其它类似场景。

三,包的工程具体怎么做呢?

3.1 基于一个常规的vue的工程,我这边使用vue cli3.0自动生成的工程,使用ts。此处先省略创建过程。
3.2 例如:在vue工程src\components目录下,创建一个查询框组件

vue文件:

<template>
    <div class="textSearch">
        <i class="iconfont  icon-search"></i>
        <input placeholder="请输入搜索关键字" @input="handleInput"/>
    </div>
</template>

<script lang="ts" src="./TextSearch.ts"></script>
<style lang="scss" scoped src="./TextSearch.scss" ></style>

ts文件:

import { Component, Vue, Prop } from 'vue-property-decorator'

@Component({})
export default class TextSearch extends Vue {
    @Prop() private searchInputHandle:any;

    private handleInput (event:any) {
        const value = event.target.value
        this.$emit('searchInputHandle', value)
    }
}

scss文件:

.textSearch {
    display: flex;
    background-color: white;
    position: relative;
    border-bottom: 1px solid #ddd;
    input{
        height: 30px;
        padding: 20px 10px;
        padding-left: 40px;
        margin:20px 30px;
        font-size: 30px;
        border: 0;  
        flex:1;
        background-color: #f8f8f8;
        border-radius: 10px;
    }
    .iconfont{
        position: absolute;
        top: 50%;
        font-size: 32px;
        left:34px;
        margin-top:-16px;
    }
}
3.3 在组件文件夹src\components\TextSearch下,创建一个index.js文件,导出一个插件

index.js文件:

import TextSearch from "./TextSearch.vue"
TextSearch.install = Vue => Vue.component(TextSearch.name, TextSearch);
export default TextSearch;
3.4 在组件文件夹src下,创建一个index.js和一个index.d.ts文件。

index.js :把封装的多个组件统一对外导出一个模块

import ListItem from "./components/ListItem";
import TextSearch from "./components/TextSearch";

export {
    ListItem,
    TextSearch
}

index.d.ts 作用定义一个ts模块,到时候引用时候不报ts模块警告

declare module 'qmh-library';
3.5 修改package.json

重点:private设置为false,mian代表入口文件,types:设置ts模块入口文件,files:上传到npm服务器必备文件

{
  "name": "qmh-library",
  "version": "1.0.6",
  "description": "组件库",
  "private": false,
  "main": "./src/index.js",
  "types": "./src/index.d.ts",
  "files": [
    "src/components/*",
    "src/index.js",
    "src/index.d.ts"
  ],
}
3.6 发布npm包

1.访问https://www.npmjs.com/注册一个账号
2.回到vue工程的终端窗口
登录

npm login

确认登录成功

npm who am i

发布

npm publish

四,发布成功后怎么项目上使用呢?

4.1在vue工程上使用,先安装npm包
npm i qmh-library -S
4.2在入口引入相关组件
import {TextSearch,ListItem} from "qmh-library"
Vue.use(TextSearch)
Vue.use(ListItem)
4.3在业务页面使用相关组件
<template>
  <div class="home">
    <TextSearch></TextSearch>
    <ListItem headText="aaa"></ListItem>
  </div>
</template>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。