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#使用包管理器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM