Most of the usual development projects directly use Alibaba's iconfont font icon library, so how to use the svg icon?
1. Install `vite-plugin-svg-icons`
npm i vite-plugin-svg-icons -D
2. Configure vite.config.ts
import { UserConfigExport, ConfigEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
export default ({ command }: ConfigEnv): UserConfigExport => {
return {
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
symbolId: "icon-[dir]-[name]",
})
],
};
};
3. Modify the main.ts file
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
//svg插件需要配置代码
import "virtual:svg-icons-register";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
const app = createApp(App);
app.use(ElementPlus).mount("#app");
4. Add the .svg icon file under the project folder src/assets/icons folder, we can copy the svg in the Alibaba icon library
Note that the file path should be consistent with iconDirs: [path.resolve(process.cwd(), "src/assets/icons")] in vite.config.ts
5. Use svg in components
<template>
<svg style="width:100px; height:100px">
<use xlink:href="#icon-home" fill="red"></use>
</svg>
</template>
If modifying the color of the fill icon fails, open the corresponding .svg file and find `fill="#d4237a"` and delete it