npm install vite-plugin-svg-icons -D
- import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
- import path from 'path'
- export default () => {
- return {
- plugins: [
- createSvgIconsPlugin({
- // Specify the icon folder to be cached
- iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
- // Specify symbolId format
- symbolId: 'icon-[dir]-[name]',
- }),
- ],
- }
- }
- //SVG插件必须的配置
- import 'virtual:svg-icons-register'
阿里巴巴图标库或者其他图标库下载SVG代码,复制到对应的文件中
- <div>
-
- <svg style="width: 30px; height: 30px;">
-
-
- <use xlink:href="#icon-base" fill="blue">use>
- svg>
- div>
-
- <script setup lang="ts">script>
-
- <style scoped lang="scss">style>
- <svg :style="{ width, height }">
- <use :xlink:href="prefix + name" :fill="color">use>
- svg>
-
- <script setup lang="ts">
- defineProps({
- //xlink:href属性值的前缀
- prefix: {
- type: String,
- default: '#icon-'
- },
- //svg矢量图的名字
- name: String,
- //svg图标的颜色
- color: {
- type: String,
- default: ''
- },
- //svg宽度
- width: {
- type: String,
- default: '16px'
- },
- //svg高度
- height: {
- type: String,
- default: '16px'
- }
- })
- script>
-
- <style scoped lang="scss">style>
- <div>
- <SvgIcon name="base" width="30px" height="30px" color="blue">SvgIcon>
- div>
-
- <script setup lang="ts">
- import SvgIcon from '@/components/Svg/index.vue'
- script>
-
- <style scoped lang="scss">style>
- //引入全局组件
- import SvgIcon from './SvgIcon/index.vue';
- import type { App, Component } from 'vue';
- //全局对象
- const components: { [name: string]: Component } = { SvgIcon };
- //对外暴露插件对象
- export default {
- //insatll方法
- install(app: App) {
- //注册项目为全局组件(可注册多个)
- Object.keys(components).forEach((key: string) => {
- //注册全局组件
- app.component(key, components[key]);
- })
- }
- }
- import gloablComponent from './components/index';
- app.use(gloablComponent);
- <div>
- <SvgIcon name="base" width="30px" height="30px" color="blue">SvgIcon>
- div>
-
- <script setup lang="ts">script>
-
- <style scoped lang="scss">style>