vite vue引入svg图标及封装
svg特征
- Preloading所有图标都是在项目运行时生成的,只需要操作一次dom即可。
- 高性能内置缓存,仅在文件被修改时才会重新生成。
一、如何使用
1.安装vite-plugin-svg-icons插件
node version: >=12.0.0
vite version: >=2.0.0
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D
2.使用插件
import { VantResolver } from 'unplugin-vue-components/resolvers'
+import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
+import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
Components({
dts: false,
resolvers: [VantResolver({ importStyle: false })]
}),
+ createSvgIconsPlugin({
+ // 指定图标文件夹,绝对路径(NODE代码)
+ iconDirs: [path.resolve(process.cwd(), 'src/icons')]
+ })
],
目录结构
3. 全局引入
main.ts
import 'virtual:svg-icons-register'
4. 使用
<svg aria-hidden="true">
<!-- #icon-文件夹名称-图片名称 -->
<use href="#icon-login-eye-off" />
</svg>
二、封装
components/CpIcon.vue
/*
* @author: aqiang
* @date: 2023-03-08 21:24:37
* @desc:
*/
<script setup lang="ts">
// 提供name属性即可
defineProps<{
name: string
}>()
</script>
<template>
<svg aria-hidden="true" class="cp-icon">
<use :href="`#icon-${name}`" />
</svg>
</template>
<style lang="scss" scoped>
.cp-icon {
// 和字体一样大
width: 1em;
height: 1em;
}
</style>
提供使用时提示 类型 types/components.d.ts
import CpIcon from '@/components/CpIcon.vue'
declare module 'vue' {
interface GlobalComponents {
CpIcon: typeof CpIcon
}
}
有些图标可以根据 style 中
color
的值来设置颜色,图标是否有这个功能取决于 UI 做图片时否开启
使用