vue3 + vite / webpack + ts 使用svg
在 webpack 中加载 svg 资源可以使用 svg-sprite-loader,而 vite 中可以使用插件 vite-plugin-svg-icons。
vite中使用
安装vite-plugin-svg-icons
npm install vite-plugin-svg-icons
// 或
yarn add vite-plugin-svg-icons
配置vite
在vite.config.ts中配置插件
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
...
plugins: [
....
createSvgIconsPlugin({
// 要缓存的svg图标文件夹,需要识别的svg都应该放在这个文件夹内
iconDirs: [path.resolve(__dirname, 'src/assets/svg-icon')],
// 指定symbolId格式--> icon-name
symbolId: 'icon-[name]'
})
],
在main.ts中注册脚本
import 'virtual:svg-icons-register'
在components/svg-icon/下创建一个公共svg-icon.vue组件
// 组件 *components/svg-icon/index.vue* 完整代码如下:
<template>
<svg
class="svg-icon"
:class="className"
aria-hidden="true">
<use :xlink:href="`#icon-${icon}`" :fill="color"/>
</svg>
</template>
<script lang="ts" setup>
const props = defineProps({
// SVG 图标名称L
icon: {
type: String,
required: true
},
// 图标类名
className: {
type: String,
default: ''
},
// svg颜色
color: {
type: String,
default: '#000'
}
})
</script>
<style scoped lang="scss">
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
overflow: hidden;
}
</style>
在main.ts中注册全局组件
import SvgIcon from '@/components/svg-icon/index.vue'
...
app.component('svg-icon', SvgIcon)
使用
<template>
<svg-icon icon="vue" className="start-page"></svg-icon>
</template>
<script lang="ts" setup>
</script>
<style scoped lang="less">
.start-page{
width:300px;
height: 210px;
color: red;
}
</style>
注意如果需要修改svg颜色需要修改svg文件内容
webpack中使用
下载svg-sprite-loader插件
npm install svg-sprite-loader
配置vue.config中配置
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = defineConfig({
chainWebpack(config) {
config.module.rule('svg').exclude.add(resolve('src/icons')).end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
})