vite按需加载element-plus,减少项目体积,你必须学会

1.在项目中安装

$ npm install element-plus --save

$ yarn add element-plus

$ pnpm install element-plus

2.安装对应的插件

npm install -D unplugin-vue-components unplugin-auto-import

3.在vite.config.ts中引入

<!-- vite.config.ts 代码结束 -->
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 下面这三行是引入组件
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// 上面这上行是新增的哈
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 自动引入组件和自动注册 new add
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    // 按需引入结束
  ]
})

使用按钮

<template>
  <el-row class="mb-4">
    <el-button plain>Plain</el-button>
    <el-button type="primary" plain>Primary</el-button>
    <el-button type="success" plain>Success</el-button>
    <el-button type="info" plain>Info</el-button>
    <el-button type="warning" plain>Warning</el-button>
    <el-button type="danger" plain>Danger</el-button>
  </el-row>

  <el-row>
    <el-button :icon="Search" circle />
    <el-button type="primary" :icon="Edit" circle />
    <el-button type="success" :icon="Check" circle />
    <el-button type="info" :icon="Message" circle />
    <el-button type="warning" :icon="Star" circle />
    <el-button type="danger" :icon="Delete" circle />
  </el-row>
</template>

<script lang="ts" setup>
// 字体图标需要你引入的哈,别忘记下载图标 npm install @element-plus/icons-vue
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
</script>

项目中会多两个文件

components.d.ts
auto-imports.d.ts : 你在element-plus中使用的组件,在这个文件中会自动引入的。
需要注意的是:auto-imports.d.ts文件会自动引入你使用的组件。它是会新增组件不会删除组件。
也就说如果你 使用某一天将项目中的 el-button 组件删除了。
auto-imports.d.ts 并不会将这个组件自动删除,仍然保留。此时需要你手动删除

使用icons-vue图标

如果你使用了icons-vue你还需要下载这样一个包
# NPM
$ npm install @element-plus/icons-vue
# Yarn
$ yarn add @element-plus/icons-vue
# pnpm
$ pnpm install @element-plus/icons-vue

参考的地址有
https://www.cnblogs.com/aloneer/p/15646354.html
https://blog.csdn.net/filerat/article/details/123750595
https://element-plus.gitee.io/zh-CN/guide/installation.html#使用包管理器

posted @   南风晚来晚相识  阅读(1129)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示