生成 svg 雪碧图


安装

node version: >=12.0.0

vite version: >=2.0.0

1
2
3
4
5
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

配置

  • vite.config.ts 中的配置插件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

export default () => {
return {
plugins: [
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
/**
* custom dom id
* @default: __svg__icons__dom__
*/
customDomId: '__svg__icons__dom__',
}),
],
}
}
  • 在main.ts引入注册脚本
1
import "virtual:svg-icons-register";

新建组件

  • 在components下新建SvgIcon.vue
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
<template>
<svg aria-hidden="false" class="icon">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
export default defineComponent({
name: 'SvgIcon',
props: {
prefix: {
type: String,
default: 'icon',
},
name: {
type: String,
required: true,
},
color: {
type: String,
default: '#333',
},
},
setup(props: any) {
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
return { symbolId }
},
})
</script>

<style scoped lang="scss">
.icon {
width: 100%;
height: 100%;
}
</style>
  • icons目录
1
2
3
4
5
6
# src/assets/icons

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg
  • 使用
1
2
3
4
5
6
<div>
<SvgIcon name="icon1"></SvgIcon>
<SvgIcon name="icon2"></SvgIcon>
<SvgIcon name="icon3"></SvgIcon>
<SvgIcon name="dir-icon1"></SvgIcon>
</div>

Typescript 支持

1
2
3
4
5
6
// tsconfig.json
{
"compilerOptions": {
"types": ["vite-plugin-svg-icons/client"]
}
}

symbolId的相关配置说明请查阅参考来源


来源:vite-plugin-svg-icons