参考官网: element plus 按需自动导入
前提:需要完成 自动导入 的安装和配置,参考:vite 配置 - 自动导入
# 1. 安装 Element Plus
| npm install element-plus | 
# 2. 安装自动导入 Icon 依赖
| npm i -D unplugin-icons | 
# 3.vite.config.ts 配置
参考: element-plus-best-practices - vite.config.ts
| // vite.config.ts | |
| import vue from "@vitejs/plugin-vue"; | |
| import { UserConfig, ConfigEnv, loadEnv, defineConfig } from "vite"; | |
| import { ElementPlusResolver } from "unplugin-vue-components/resolvers"; | |
| import Icons from "unplugin-icons/vite"; | |
| import IconsResolver from "unplugin-icons/resolver"; | |
| export default ({ mode }: ConfigEnv): UserConfig => { | |
| return { | |
| plugins: [ | |
| AutoImport({ | |
| resolvers: [ | |
|                     // 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式) | |
| ElementPlusResolver(), | |
|                     // 自动导入图标组件 | |
| IconsResolver({}), | |
|                 ] | |
|                 // 是否在 vue 模板中自动导入 | |
| vueTemplate: true, | |
|                 // 自动导入组件类型声明文件位置,默认根目录 | |
| dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts') | |
| }), | |
| Components({ | |
| resolvers: [ | |
|         			// 自动导入 Element Plus 组件 | |
| ElementPlusResolver(), | |
|             		// 自动注册图标组件 | |
| IconsResolver({ | |
|                         //element-plus 图标库,其他图标库 https://icon-sets.iconify.design/ | |
| enabledCollections: ["ep"] | |
| }), | |
| ], | |
|                 //  自动导入组件类型声明文件位置,默认根目录 | |
| dts: path.resolve(pathSrc, "types", "components.d.ts"), | |
| }), | |
| Icons({ | |
|                  // 自动安装图标库 | |
| autoInstall: true, | |
| }), | |
| ], | |
| 	} | |
| } | 
# 4. 在 main.ts 引入
注意:按需引入时,element-plus 不需要在
main.ts中引入,插件会自动挂载处理,可以在全局直接使用
这里在 main.ts 中引入 element-plus 样式与图标
| import * as ElementPlusIconsVue from '@element-plus/icons-vue'; // 引入图标 | |
| import 'element-plus/dist/index.css'; // 引入样式 | |
| //... | |
| for (const [key, component] of Object.entries(ElementPlusIconsVue)) { | |
| app.component(key, component); | |
| } | 
# 5. 示例代码
| <!-- src/components/HelloWorld.vue --> | |
| <div> | |
| <el-button type="success"><i-ep-SuccessFilled />Success</el-button> | |
| <el-button type="info"><i-ep-InfoFilled />Info</el-button> | |
| <el-button type="warning"><i-ep-WarningFilled />Warning</el-button> | |
| <el-button type="danger"><i-ep-WarnTriangleFilled />Danger</el-button> | |
| </div> | 
