使用插件自动引入 svg 图标

依赖安装

1
pnpm i -D unplugin-icons vite-plugin-svg-icons @vitejs/plugin-vue

配置 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
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

import { NaiveUiResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";

import { resolve } from "path";
import { FileSystemIconLoader } from "unplugin-icons/loaders";
import IconsResolver from "unplugin-icons/resolver";
import Icons from "unplugin-icons/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

// svg存放地址
const customIconPath = resolve(process.cwd(), "src/assets/svg");

export default defineConfig({
return {
plugins: [
vue(),
Components({
// auto import components 自动加载组件
resolvers: [
NaiveUiResolver(),
IconsResolver({
customCollections: ["custom"],
componentPrefix: "icon",
}),
],
dts: false,
}),
Icons({
compiler: "vue3",
customCollections: {
custom: FileSystemIconLoader(customIconPath),
},
scale: 1,
defaultClass: "inline-block",
}),
createSvgIconsPlugin({
iconDirs: [customIconPath],
symbolId: "icon-custom-[dir]-[name]",
inject: "body-last",
customDomId: "__CUSTOM_SVG_ICON__",
}),
],
};
});

在这里我们为什么要使用 `process.cwd()`呢?

`__dirname和process.cwd()的区别`
1
2
3
4
5
6
const { resolve } = require("path")

const dirnamePath = resolve(__dirname, "")
console.log(dirnamePath)
const pwdPath = resolve(process.cwd())
console.log(pwdPath)
输出结果是:
1
2
/Users/wangmou/workspace/whbbit-blog/wxw-blog/scripts
/Users/wangmou/workspace/whbbit-blog/wxw-blog
我们可以看到,`__dirname` 是命令执行目录,`process.cwd()` 是执行命令的 js 所的在目录

使用

假设 assets/svg 文件夹中包含 logo.svg 和 menu.svg 两个 svg 图标。我们可以直接使用 icon-custom-文件名 来使用

1
2
3
4
<template>
<icon-custom-logo />
<icon-custom-menu />
</template>