如何自己封装一个VUE3的UI组件库?


  // 打包配置
  build: {
    sourcemap: false, //不开启镜像
    outDir: 'AsaiUI',
    assetsInlineLimit: 8192, // 小于 8kb 的导入或引用资源将内联为 base64 编码
    terserOptions: {
      // 生产环境移除console
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    lib: {
      entry: resolve(process.cwd(), './packages/components/index.ts'), // 设置入口文件
      name: 'asai-ui', // 起个名字,安装、引入用
      fileName: (format) => `asai-ui.${format}.js`, // 打包后的文件名
    },
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ['vue', 'tailwindcss', '@element-plus/icons-vue'],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          vue: 'Vue',
          tailwindcss: 'tailwindcss',
          '@element-plus/icons-vue': '@element-plus/icons-vue',
        },
      },
    },
  },

将上面的配置vite.config.ts

文件目录结构如下

打包的入口文件components/index.ts

import { App } from 'vue';
export * from './button';
export * from './tag';

import button from './button';
import tag from './tag';

const components = [button, tag];

export default {
  install(app: App) {
    components.map((item) => item.install(app));
  },
};

 组件的导出文件components/button/index.ts

import AsButton from "./src/as-button.vue";
import { App } from "vue";

export default {
  install(app: App) {
    app.component("AsButton", AsButton);
  },
};

export { AsButton };

组件的Vue文件components/button/src/as-button.vue

<script setup lang="ts">
import { ref } from 'vue';
const count = ref(0);

defineProps({
  title: String,
});

const emit = defineEmits(['click']);

const clickEmit = () => {
  count.value++;
  emit('click', count.value);
};
</script>

<template>
  <button class="as-button" @click="clickEmit()">{{ title }}{{ count }}</button>
</template>

<style scoped>
.as-button {
  font-size: 38px;
  background-color: bisque;
}
</style>

打包的包如何使用(发布的话正常NPM去)

1. 项目的入口文件main.ts中引入

// 自封的UI
import AsaiUI from '../AsaiUI/asai-ui.es';
import "../AsaiUI/style.css"

const app = createApp(App);
app.use(AsaiUI);

2. 然后这么调用即可

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿赛工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值