vite构建Vue3组件并发布npm包

2,046 阅读4分钟

前言

在项目开发过程中当,遇到公共部分,我们首先会在此项目中封装一个公共组件,并通引用使用。但是当我们在多个项目中均使用到此组件呢,难道要每个项目均复制相同的组件吗,这真的是费时费力的行为。

此时,我们想到的是自己发布一个组件或者组件库,将项目中同类型的组件封装在组件库中并通过npm 安装使用。

开发

1 创建基础的vite 脚手架

pnpm create vite npm-package --template vue

npm-package 为包名,之后按照提示安装依赖,启动项目

2 删除无用文件

  1. 删除src下的assets文件
  2. 删除src下components下文件
  3. 清空App.vue中的文件内容,后续做测试使用

3 组件封装

  1. 在src\components文件创建文件夹button添加index.vue的文件
  2. 封装我们要使用的组件
<template>
  <span v-if="popConfirm" :style="{width: '100%'}">
    <el-popconfirm
      :title="popTitle"
      :teleported="teleported"
      @confirm="confirmEvent"
      :width="popWidth">
      <template #reference>
        <el-button
          class="gl-button"
          :size="size"
          :type="type === 'text' ? '' : type"
          :link="type === 'text' || link"
          :disabled="disabled"
          :icon="icon">
          <slot />
        </el-button>
      </template>
    </el-popconfirm>
  </span>
  <el-button
    v-else
    class="gl-button"
    :size="sizes[size]"
    :type="type === 'text' ? '' : type"
    :link="type === 'text' || link"
    :plain="false"
    :disabled="disabled"
    :icon="icon">
    <slot />
  </el-button>
</template>
<script>
import { h, defineComponent, computed } from 'vue'
const sizes = {
  small: 'small',
  large: 'large',
  mini: 'mini',
  default: null
}
export default defineComponent({
  name:'TestButton',
  emits: ['confirm'],
  props: {
    link: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'default'
    },
    size: {
      type: String,
      default: null,
      validator: (val) => {
        return val ? Object.prototype.hasOwnProperty.call(sizes, val) : true
      }
    },
    icon: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    popConfirm: {
      type: Boolean,
      default: false
    },
    popTitle: {
      type: String,
      default: '请确认执行此操作?'
    },
    teleported: {
      type: Boolean,
      default: true
    },
    popWidth: {
      type: Number,
      default: null
    }
  },
  setup(props, { emit }) {
    const confirmEvent = () => {
      emit('confirm')
    }
    return {
      sizes,
      confirmEvent
    }
  }
})
</script>

<style scoped>
</style>

4 导出组件

src\components文件夹下新建index.js用于导出组件

import TestButton from './button/index.vue'

// 按需引入
export { TestButton };

const component = [TestButton];

const install = function (App) {
    component.forEach((item) => {
        console.log('come in item', item)
        App.component(item.name, item);
    });
}

export default { install }

5 验证组件是否可用

  1. src\main.js注册组件
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import VuePlus from "./components/index.js"; //导入
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

createApp(App).use(ElementPlus).use(VuePlus).mount('#app')

  1. 在App.vue中使用此组件
<template>
  <div>
    <test-button>我的世界</test-button>
  </div>
</template>
<script setup>
</script>

<style>

</style>

  1. vscode中运行终端npm run dev

打包配置

1 配置vite.config.js文件

先看下初始化文件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
})

针对上述文件需要修改,详情可参照Vite构建生产版本

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path"

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  build: {
    outDir: 'xxxxx',//输出文件名
    // 库编译模式配置
    lib: {
      entry: path.resolve(__dirname, "./src/components/index.js"), //指定组件编译入口文件
      name: "xxxxx",
      fileName: "xxxxx",
    },
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ['vue'],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          vue: 'Vue',
        },
      },
    },
  }
})
  1. 之后使用npm run build可以看到打包文件如下入所示

2 上传准备:配置package.json

在xxxx目录下,打开终端,然后执行npm init -y命令初始化package.json package.json是用来配置我们上传到npm仓库的的版本号等配置,这个在每次修改上传之前一定要记得修改哦

{
  "name": "vue3-corn-plus",
  "version": "1.0.0",
  "description": "",
  "main": "vue3-corn-plus.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

我们在上传之前记得修改keywords,方便用户可以搜索

上传到npm

  1. 注册账号 我们先去npm官网注册账号,切记要记住用户名、密码和邮箱
  2. 设置npm镜像源为官方镜像源
npm config set registry=https://registry.npmjs.org
  1. 登录npm

    • 在打包后的文件根目录打开终端,输入npm login登录到官网

    • 出现如下情况即为登录成功

    • npm.png

  2. 推送到npm仓库

    • 3中所述的终端中填写发布命令,npm publish
    • 注意点:发布前要保证没有相同的包名,否则无法发布,每次发布的版本号必须不同
  3. npm网站上搜索此包名,查看相关组件

下载使用

1 安装

npm i vue3-cron-plus-picker 或者 pnpm add vue3-cron-plus-picker

2 引入

  1. 全局引入 在src\main.js中引入下载的包,并引入其样式
    import { createApp } from 'vue'
    import './style.css'
    import App from './App.vue'
    import Vue3Cron from 'vue3-cron' // 引入组件
    import 'vue3-cron/style.css' //引入组件相关样式
    
    createApp(App).use(Vue3Cron).mount('#app')
    
    
  2. 局部引入 在使用的组件的vue文件中直接引入
    import 'vue3-cron/style.css'
    import {Vue3Cron} from 'vue3-cron'
    

3 使用

  <template>
  <div>
      <vue3-cro/>
  </div>
</template>

<script setup>
</script>
<style>
</style>

4 验证

使用npm run dev启动项目查看效果,出来对应组件即为成功