简体   繁体   English

Webpack2-如何内联SVG文件

[英]Webpack2 - How to inline an SVG file

In webpack.config.js I am using the following loader : webpack.config.js我正在使用以下loader

{
  test: /\.svg$/,
  use: [ 'file-loader' ]
}

Then in my component : 然后在我的component

import icon from '../img/icons/menu.svg'

However, console.log(icon) // 58f714c05099311f302aeb7d346be056.svg shows that the value of icon is just a filename. 但是, console.log(icon) // 58f714c05099311f302aeb7d346be056.svg显示icon的值只是一个文件名。

Is there a way to import the raw svg ? 有没有办法导入原始svg

Update: 更新:

Using url-loader imports the svg as a base64 string. 使用url-loader svg导入为base64字符串。

<img src="data:image/svg+xml;base64,PHN2ZyBjbGFzcz0ibWVudS1pY29uIiB3aWR0aD0iMzBweCIgaGVpZ2h0PSIzMHB4IiB2aWV3Qm94PSIwIDAgMzAgMzAiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik00LDEwaDI0YzEuMTA0LDAsMi0wLjg5NiwyLTJzLTAuODk2LTItMi0ySDRDMi44OTYsNiwyLDYuODk2LDIsOFMyLjg5NiwxMCw0LDEweiBNMjgsMTRINGMtMS4xMDQsMC0yLDAuODk2LTIsMiAgczAuODk2LDIsMiwyaDI0YzEuMTA0LDAsMi0wLjg5NiwyLTJTMjkuMTA0LDE0LDI4LDE0eiBNMjgsMjJINGMtMS4xMDQsMC0yLDAuODk2LTIsMnMwLjg5NiwyLDIsMmgyNGMxLjEwNCwwLDItMC44OTYsMi0yIFMyOS4xMDQsMjIsMjgsMjJ6Ii8+PC9zdmc+Cg==">

However, this also is not ideal since I am not able to style the svg with CSS . 但是,这也不理想,因为我无法使用CSS设置svgCSS

module.loaders =  ...
  {
      test: /\.(svg)$/,
      loader: 'raw-loader'
  }

This is because you are having the inline svg. 这是因为您拥有内联svg。 Ref 参考

You can use svg as background image with plugin https://github.com/kisenka/svg-fill-loader : 您可以通过插件https://github.com/kisenka/svg-fill-loader将svg用作背景图像:

background-image: url('./styles/images/shark.svg?fill=$ddd');
background-size: cover;
width: 330px;
height: 250px;

With background-size: cover; background-size: cover; svg will stretch across the container, so you can adjust size, and with fill you can change the color of the svg. svg会在容器上延伸,因此您可以调整大小,并通过fill可以更改svg的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM