如何使用webpack设置内嵌svg [英] how to set up an inline svg with webpack

查看:575
本文介绍了如何使用webpack设置内嵌svg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用webpack设置内嵌svg?

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

我正在关注 react-webpack-cookbook .

我已使用文件加载器正确设置了 webpack.config .

I have my webpack.config set up correctly with the file loader.

但是该示例显示的是使用这样的背景图像:

However the example shows using a background image like this:

.icon {
   background-image: url(./logo.svg);
}

效果很好,但是我想拥有一个内嵌svg图像,该如何将我的 logo.svg 内联包含在我的react组件中?

which works fine, but I want to have an inline svg image how do I do this to include my logo.svg inline in my react component?

import React, { Component } from 'react'

class Header extends Component {

  render() {
    return (
        <div className='header'>
            <img src={'./logo.svg'} />
        </div>
    );
  }
};

export default Header

推荐答案

实际上,米歇尔的回答为我指明了正确的方向,这非常适合通过webpack加载svg文件并将其用作<img> src

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

但是实际上要获得内嵌svg,我需要执行以下操作:

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

使用 svg-inline-loader 代替svg加载器:

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

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

然后将svg内联加载到组件中:

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

似乎有一个用于响应的内嵌svg包装器 svg-inline-react 这将是另一种选择,而不是<div dangerouslySetInnerHTML={{__html: mySvg}} />

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}} />

这篇关于如何使用webpack设置内嵌svg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆