React如何使用SVG Symbol插入图片

128 阅读1分钟

1、导出webpack.config.js

首先将你的文件commit之后执行

yarn eject

这会导出你的config文件 导出之后请立即commit,养成良好习惯,以防文件丢失形成不可挽回的局面

2、进入webpack.config.js文件

找到

module: {
  strictExportPresence: true,
  rules: [
    // Handle node_modules packages that contain sourcemaps
    shouldUseSourceMap && {
      enforce: 'pre',
      exclude: /@babel(?:/|\{1,2})runtime/,
      test: /.(js|mjs|jsx|ts|tsx|css)$/,
      loader: require.resolve('source-map-loader'),
    },
    {
      // "oneOf" will traverse all following loaders until one will
      // match the requirements. When no loader matches it will fall
      // back to the "file" loader at the end of the loader list.
      oneOf: [
        // TODO: Merge this config once `image/avif` is in the mime-db
        // https://github.com/jshttp/mime-db

在oneOf里边的数组里加入下面的代码

{
  test: /.svg$/,
  use: [
    { loader: 'svg-sprite-loader', options: {} },
    {loader: 'svgo-loader',options: {
      plugins:[
        {removeAttrs:{attrs:'fill'}}
      ]
      }}
  ]
},

完成以后再执行

yarn add --dev svg-sprite-loader
yarn add --dev svgo-loader

在你想要使用图片的地方require('你的文件路径'),调用方法

<svg>
    <use xLinkHref='#xxx'></use>
</svg>

# 不能少哦,后面的xxx就是你的文件的名字,比如文件money.svg的名字就是money