拿到React配置
yarn eject
然后根据 svg-sprite-loader文档进行配置
对eject生成的config/webpack.config.js进行配置
将你搜索到的svg-sprite-loader规则添加到oneOf中,
module:{
rules:[
{
//第一次运行oneOf
oneOf:[
...
]
}
]
}
防止TreeShaking
TreeShaking会将没有使用的依赖自动删除(从依赖树上摇下来),这也是为了减少不必要的开销。
例如使用import引入SVG
import svg1 from 'icon/svg1'
console.log(svg1) //使用了SVG就不会被`TreeShaking`
在页面中检查元素会看到:页面中引入了SVG标签。
这时我们就可以正常使用svg
<svg>
<use xlink:href="#<symbol中的id>"></use>
</svg>
那难道每次使用都要console.log(x)一下吗。可以使用require来引入,require不支持TreeShaking。
遍历文件夹引入所有svg
const importAll = (requireContext: __WebpackModuleApi.RequireContext) => requireContext.keys().forEach(requireContext);
try {importAll(require.context('../assets/icons', true, /\.svg$/));} catch (e) {console.log(e);}