インストール#
npm install vite-plugin-svg-icons --save-dev
設定#
-
vite.config.ts
で設定を行いますimport { defineConfig } from "vite"; import { createSvgIconsPlugin } from "vite-plugin-svg-icons"; import vue from "@vitejs/plugin-vue"; import path from "path"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")], symbolId: "icon-[dir]-[name]", }), ], });
-
プロジェクトの
src/assets
ディレクトリにicons/svg
ディレクトリを作成し、svg アイコンファイルを配置します -
main.ts
でインポートしますimport "virtual:svg-icons-register";
-
コンポーネント
SvgIcon.vue
を定義します<template> <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName" :fill="props.color" /> </svg> </template> <script lang="ts" setup> import { computed } from "vue"; const props = defineProps({ iconClass: { type: String, required: true, }, className: { type: String, default: "", }, color: { type: String, default: "", }, }); const iconName = computed(() => `#icon-${props.iconClass}`); const svgClass = computed(() => { if (props.className) { return `svg-icon ${props.className}`; } return "svg-icon"; }); </script> <style scope lang="scss"> .sub-el-icon, .nav-icon { display: inline-block; font-size: 15px; margin-right: 12px; position: relative; } .svg-icon { width: 1em; height: 1em; position: relative; fill: currentColor; vertical-align: -2px; } </style>
-
main.ts
でグローバルコンポーネントとして登録しますimport svgIcon from "./components/SvgIcon/index.vue"; app.component("svg-icon", svgIcon);
使用方法#
<template>
<div style="display: flex; gap: 20px">
<svg-icon iconClass="Github"></svg-icon>
<svg-icon iconClass="Aiming"></svg-icon>
</div>
</template>
<script setup lang="ts">
</script>
<style lang="scss" scoped>
</style>