how to set up an inline svg with webpack

后端 未结 9 1906
感动是毒
感动是毒 2020-12-02 16:49

I am wondering how to set up an inline svg with webpack?

I am following the react-webpack-cookbook.

I have my webpack.config set up correc

相关标签:
9条回答
  • 2020-12-02 17:34

    Actually Michelle's answer pointed me in the right direction, and that works nicely for loading an svg file with webpack and using it as your <img> src

    However to actually get the inline svg, I needed to do the following:

    Instead of file-loader use svg-inline-loader as your svg loader:

    { test: /\.svg$/, loader: 'svg-inline-loader' }

    Then to load the svg inline in a component:

    import React, { Component } from 'react'
    import logo from "./logo.svg";
    
    class Header extends Component {
    
      render() {
        return (
            <div className='header'>
              <span dangerouslySetInnerHTML={{__html: logo}} />
            </div>
        );
      }
    };
    
    export default Header
    

    It looks like there is an inline svg wrapper for react svg-inline-react which would be another option instead of the <div dangerouslySetInnerHTML={{__html: mySvg}} />

    0 讨论(0)
  • 2020-12-02 17:36

    Similar to another answer using React, there is also a handy Vue plugin as well.

    vue-svg-loader just throw it in your configuration and start using. The nice thing is it will also run your svg through SVGO to optimize it.

    Configuration

    {
        test: /\.svg$/,
      loader: 'vue-svg-loader', // `vue-svg` for webpack 1.x
      options: {
        // optional [svgo](https://github.com/svg/svgo) options
        svgo: {
          plugins: [
            {removeDoctype: true},
            {removeComments: true}
          ]
        }
      }
    }
    

    Usage

    <template>
      <nav id="menu">
        <a href="...">
          <SomeIcon class="icon" />
          Some page
        </a>
      </nav>
    </template>
    
    <script>
    import SomeIcon from './assets/some-icon.svg';
    
    export default {
      name: 'menu',
      components: {
        SomeIcon,
      },
    };
    </script>
    
    0 讨论(0)
  • 2020-12-02 17:39

    Folks who use svg-inline-loader and who stuck with "Cannot find module" error try to install babel-plugin-inline-react-svg and add it to the babel plugins:

    "plugins": [
        ...
        ["inline-react-svg", {}]
    ],
    ...
    
    0 讨论(0)
提交回复
热议问题