- 安装
npm install vite-svg-loader --save-dev
- vite.config.js配置
import svgLoader from 'vite-svg-loader'
export default defineConfig({
plugins: [vue(), svgLoader()]
})
- 特别注意
vite-env.d.ts中添加,否则打包报错
/// <reference types="vite/client" />
/// <reference types="vite-svg-loader" />
- 使用
import SvgImage from './src/assets/my-image.svg?url'
<img :src="SvgImage" alt="My image" />
import SvgImage from './src/assets/my-image.svg?raw'
<div class="svg-image" v-html="SvgImage"></div>
.svg-image:hover {
color: green
}
import SvgImage from './src/assets/my-image.svg?component'
<SvgImage width="20" />
- 动态组件引入
- 在src下创建icons,图标放在该目录下
- 在src/components下创建SvgIcon文件夹,在SvgIcon下创建index.vue
<template>
<component :is="dynamicIcon" v-bind="$attrs" />
</template>
<script lang="ts" setup>
import { onMounted, shallowRef } from "vue";
const props = defineProps({
name: {
type: String,
required: true,
},
});
const dynamicIcon = shallowRef<any>("");
const loadSvgIcon = async (iconName: string) => {
try {
// 动态导入SVG文件,这里假设SVG文件都在src/assets/icons目录下
const { default: icon } = await import(
/* @vite-ignore */ `../../icons/${iconName}.svg?component`
);
// 将导入的SVG文件设置为组件
dynamicIcon.value = icon;
} catch (error) {
console.error("Error loading SVG icon:", error);
}
};
onMounted(() => {
loadSvgIcon(props.name);
});
</script>
import SvgIcon from "@/components/SvgIcon/index.vue";
<SvgIcon name="air" width="77" height="49" fill="#fff" />