自动按需导入element-plus/icons


字数:536 阅读时长:2分钟 阅读:85

element官网 提供了 element-plus/icons 自动导入的方法和Vite配置模版,但是在使用过程中还是遇到了坑。

element-plus/icons 自动导入

安装依赖

1
2
3
pnpm add -S @element-plus/icons-vue

pnpm install -D unplugin-icons unplugin-auto-import

修改 vite.config.ts 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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 IconsResolver from 'unplugin-icons/resolver'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import path from 'node:path'
import UnoCSS from 'unocss/vite'
import Icons from 'unplugin-icons/vite'
import Inspect from 'vite-plugin-inspect'

// https://vitejs.dev/config/
export default defineConfig({
base: '/web/',
resolve: {
// 在导入模块时,如果模块路径不包含文件扩展名,则会尝试添加下面这些扩展名
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
// 在导入模块时,如果模块路径以 / 开头,则会尝试在下面这些目录中查找该模块
alias: {
'@': path.resolve(__dirname, './src'),
'@img': path.resolve(__dirname, './src/assets/img'),
},
},
plugins: [
vue(),
AutoImport({
// Auto import functions from Vue, e.g. ref, reactive, toRef...
// 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
imports: ['vue'],
// Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
// 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
resolvers: [
ElementPlusResolver(),
// Auto import icon components
// 自动导入图标组件
IconsResolver({
prefix: 'Icon',
}),
],
// dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
}),
Components({
resolvers: [
// Auto register icon components
// 自动注册图标组件
IconsResolver({
enabledCollections: ['ep'],
}),
// Auto register Element Plus components
// 自动导入 Element Plus 组件
ElementPlusResolver(),
],
}),
Icons({
autoInstall: true,
}),
Inspect(),
UnoCSS(),
],
})

遇到的问题

直接从官网复制 icon 组件却不能正常渲染。如下:

1
2
3
<el-icon size="20">
<Edit />
</el-icon>

正确写法:需要在官方图标集合中标识的图标名前 追加前缀 IEp 使用。

1
2
3
4
5
6
7
8
9
10
// 正确的写法是
<el-icon size="20">
<i-ep-edit-location />
</el-icon>

<!-- 或 -->

<el-button type="primary">
<el-icon><IEpSearch /></el-icon>搜索
</el-button>

欢迎访问:天问博客

本文作者: Tiven
发布时间: 2023-02-23
最后更新: 2023-07-17
本文标题: 自动按需导入element-plus/icons
本文链接: https://www.tiven.cn/p/edf876ae/
版权声明: 本作品采用 CC BY-NC-SA 4.0 许可协议进行许可。转载请注明出处!
欢迎留言,提问 ^_^
个人邮箱: tw.email@qq.com
notification icon
博客有更新,将会发送通知给您!