vite-プラグイン-svg-アイコン
- プリロードは、プロジェクトの実行中にすべてのアイコンを生成し、dom を一度だけ操作する必要があります
- ファイルが変更されたときにのみ再生成される高性能の組み込みキャッシュ
インストール
yarn add vite-plugin-svg-icons -D
npm i vite-plugin-svg-icons -D
pnpm install vite-plugin-svg-icons -D
vite.config.ts の構成プラグイン
import {
createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/icons')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
/**
* 自定义插入位置
* @default: body-last
*/
// inject?: 'body-last' | 'body-first'
/**
* custom dom id
* @default: __svg__icons__dom__
*/
// customDomId: '__svg__icons__dom__',
}),
],
}
}
src/main.js に登録スクリプトを導入する
import 'virtual:svg-icons-register'
SvgIcon コンポーネントを作成します
/src/components/SvgIcon/index.vue
<template>
<svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
<use :xlink:href="symbolId" rel="external nofollow" :fill="props.color" />
</svg>
</template>
<script setup>
import {
computed } from 'vue'
const props = defineProps({
prefix: {
type: String,
default: 'icon'
},
name: {
type: String,
required: true
},
color: {
type: String,
default: '#333'
},
size: {
type: String,
default: '1em'
}
})
const symbolId = computed(() => `#${
props.prefix}-${
props.name}`)
</script>
グローバルに登録されたコンポーネント
# src/main.js
import {
createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import svgIcon from "@/components/SvgIcon/index.vue";
import 'virtual:svg-icons-register'
createApp(App)
.use(ElementPlus)
.use(router)
.component('svg-icon', svgIcon)
.mount('#app')
使用
<template>
<svg-icon v-if="props.icon" :name="props.icon" />
<span v-if="props.title" slot='title'>{
{
props.title }}</span>
</template>
<script setup>
const props = defineProps({
icon: {
type: String,
default: ''
},
title: {
type: String,
default: ''
}
})
</script>
すべての SymbolId を取得する
import ids from 'virtual:svg-icons-names'