vite でビルドされた vue3 プロジェクトで svg アイコンを使用するにはどうすればよいですか?

1. プラグインをインストールします: vite-plugin-svg-icons 

// 通过命令安装2个插件
npm i vite-plugin-svg-icons -D
npm i fast-glob -D

 写真が示すように

//package.json
 "devDependencies": {
    "@types/node": "^18.7.13",
    "@vitejs/plugin-vue": "^3.0.3",
    "fast-glob": "^3.2.12",
    "sass": "^1.54.5",
    "typescript": "^4.6.4",
    "vite": "^3.0.7",
    "vite-plugin-svg-icons": "^2.0.1",
    "vue-tsc": "^0.39.5"
  }

2. プラグインを設定します: vite.config.ts で createSvgIconsPlugin を設定します。 

//vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { join, resolve } from "path";
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'


// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
      symbolId: 'icon-[dir]-[name]',
    }),
    
  ],
  resolve: {
    alias: {
      '@': join(__dirname, 'src'),
    }
  },
})

 ストレージファイルパス: src/assets/svg

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg

次に、main.ts に次のコードを導入します。

//main.ts
import 'virtual:svg-icons-register'

 3. コンポーネントにパッケージ化: SvgIcon.vue

<template>
    <svg aria-hidden="true" :style="{ width: size + 'px', height: size + 'px' }">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
    iconName: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: ''
    },
    size: {
        type: [Number, String],
        default: 18
    }
})
const symbolId = computed(() => `#icon-${props.iconName}`);

</script>


<style scoped>
.svg-icon {
    fill: currentColor;
    vertical-align: middle;
}
</style>

 4. 使用方法:

<template>
        <SvgIcon icon-name="icon1" ></SvgIcon>
</template>

<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon.vue";
</script>

<style scoped lang="scss">
</style>

転載先: vite でビルドした vue3 プロジェクトで svg アイコンを使用するには? - Jianshu (jianshu.com) 

おすすめ

転載: blog.csdn.net/deng_zhihao692817/article/details/131845803