本項(xiàng)目為react項(xiàng)目
image.png
簡(jiǎn)單應(yīng)用:
// 1. webpack設(shè)置svg loader,不要再在file-loader/url-loader中配置svg,只需要這里配置就夠了
// 但是如果你使用了svg字體,則不能刪除字體中的svg,但是可以使用exclude過(guò)濾調(diào)svg icon圖標(biāo),比如
// test: /\.(eot|woff|ttf|woff2|appcache|svg)\??.*$/,
// exclude: [/^node_modules$/, path.resolve(__dirname, '../src/svg')],
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
exclude: /^node_modules$/,
include: [path.resolve(__dirname, '../src/svg')],
options: {
symbolId: '[name]',
extract: false
}
}
// 使用svg Home.jsx
import '../svg/DDQY.svg'
import '../svg/DDQY_NO.svg'
...
<svg aria-hidden="true">
<use xlinkHref="#DDQY"></use>
</svg>
<svg aria-hidden="true">
<use xlinkHref="#DDQY_NO"></use>
</svg>
上面兩步就可以基本運(yùn)行,但是打包后就會(huì)發(fā)現(xiàn)打包文件夾里面根本沒(méi)有svg文件,svg被包裹進(jìn)js文件中了,即便給svg-sprite-loader設(shè)置了outputPath也沒(méi)有用。
進(jìn)一步改進(jìn)。
// 1. webpack svg loader配置
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
exclude: /^node_modules$/,
include: [path.resolve(__dirname, '../src/svg')],
options: {
symbolId: '[name]',
extract: true,
outputPath: "static/svgIcons/",
publicPath: "static/svgIcons/",
spriteFilename: "svg-sprite.svg"
// spriteFilename: svgPath => `sprite${svgPath.substr(-4)}`
}
},
// 設(shè)置了extract:true,所以還需要在plugins中引入,否則會(huì)報(bào)錯(cuò)
const SvgSpriteLoader = require('svg-sprite-loader/plugin')
...
module.exports = {
entry: {
// output的name變量值就是main
main: './src/app.js'
},
plugins: [
// new CleanWebpackPlugin(),
...
new SvgSpriteLoader()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, '../dist')
},
......
}
// 2. Home.jsx使用svg
import svgYes from '../svg/DDQY.svg'
import svgNo from '../svg/DDQY_NO.svg'
...
<svg aria-hidden="true">
<use xlinkHref={svgYes}></use>
</svg>
<svg aria-hidden="true">
<use xlinkHref={svgNo}></use>
</svg>
再次運(yùn)行,OK。
再次打包,發(fā)現(xiàn)多了個(gè)static/svgIcons/svg-sprite.svg文件,這個(gè)svg-sprite.svg文件包含了上面引入的兩個(gè)svg圖標(biāo)。
代碼還可以進(jìn)一步修改,如果svg圖標(biāo)太多,一個(gè)個(gè)引入很麻煩,就可以使用require.context()獲得目錄下所有svg圖片的map,然后循環(huán)require引入這些svg。
// components/svgCustomer.jsx
import React, { Component } from "react";
let requireSvgOb = {}
const svgMapOb = require.context('@src/svg', false, /\.svg$/);
const requireAll = (requireContext) => {
requireContext.keys().map((item) => {
let svgName;
let svgModule;
let regArr = item.match(/^.\/(.+?).svg$/);
if (Array.isArray(regArr) && regArr[1]) {
svgName = regArr[1];
svgModule = requireContext(item);
requireSvgOb[svgName] = svgModule.default
}
})
}
requireAll(svgMapOb)
console.log('requireSvgOb:', requireSvgOb)
class SvgCustomer extends Component {
constructor(props) {
super();
this.state={
}
}
UNSAFE_componentWillMount () {
}
componentDidMount () {
}
render () {
return (
<svg aria-hidden="true">
<use xlinkHref={requireSvgOb[this.props.iconName]}></use>
</svg>
)
}
}
export default SvgCustomer;
// Home.jsx
import SvgCustomer from './components/svgCustomer'
...
<SvgCustomer iconName="DDQY"></SvgCustomer>
<SvgCustomer iconName="DDQY_NO"></SvgCustomer>
React好像沒(méi)有全局引入,不能像Vue那樣直接在main.js中引入后,全局使用。
用上面的寫(xiě)法好像有點(diǎn)讓費(fèi),再修改一下,按需引入吧。
// components/svgCustomer.jsx
import React, { Component } from "react";
// .size-w100-h100 {
// width: 100%; height: 100%;
// }
class SvgCustomer extends Component {
constructor(props) {
super();
let svg = require("@src/svg/" + props.iconName + ".svg")
console.log(svg)
this.state={
svg: svg.default // svg是一個(gè)對(duì)象,svg.default才是真正的svg圖片
}
}
UNSAFE_componentWillMount () {
}
componentDidMount () {
}
render () {
return (
<svg aria-hidden="true" className="size-w100-h100">
<use xlinkHref={this.state.svg}></use>
</svg>
)
}
}
export default SvgCustomer;
// Home.jsx
import SvgCustomer from './components/svgCustomer'
...
<SvgCustomer iconName="DDQY"></SvgCustomer>
<SvgCustomer iconName="DDQY_NO"></SvgCustomer>
20201123增加一點(diǎn)Vue使用svg的代碼:
// src/components/SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ""
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}`;
},
svgClass() {
if (this.className) {
return "svg-icon " + this.className;
} else {
return "svg-icon";
}
}
}
};
</script>
<style scoped>
.svg-icon {
/* width: 1em;
height: 1em;*/
fill: currentColor;
overflow: hidden;
}
</style>
// 全局注冊(cè)SvgIcon組件
// assets/svg/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件
// register globally
Vue.component('SvgIcon', SvgIcon)
// svg圖標(biāo)太多,一個(gè)個(gè)引入很麻煩,就可以使用require.context()獲得目錄下所有svg圖片的map,然后循環(huán)require引入這些svg
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./', false, /\.svg$/)
requireAll(req)
// src/main.js
import '@/assets/svg/index.js' // 引入svg
// 普通頁(yè)面可以直接只用全局組件 iconClass就是svg文件的名字,class是樣式(設(shè)置大小位置)
<SvgIcon iconClass="down" class="down-icon"></SvgIcon></div>
vue cli3寫(xiě)法找到個(gè)更好的:http://www.lxweimin.com/p/b1a16a030f72