简体   繁体   English

svg文件中的require.context提供不同的结果

[英]require.context from svg file gives different result

I'm trying to create a react component for svg Icons so I'm trying to get context of the svg file with require.context like this 我正在尝试为svg Icons创建一个react组件,所以我正在尝试使用require.context获取svg文件的上下文

const myIcons = require.context('myIcons/', true, /^\.\/.*\.svg$/)
myIcons('./location.svg')

the problem is that I get the result as data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo... and I expect it to return something more like <svg ...><path ..></svg> like it is in the svg file. 问题是我得到的结果为data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo... ,我希望它返回类似<svg ...><path ..></svg>内容在svg文件中。

I tried to google it but I didn't find anything relevant. 我试图用Google搜索它,但是没有找到任何相关信息。 thanks 谢谢

I just faced that issue not long ago, I found this loader for webpack https://github.com/webpack-contrib/svg-inline-loader 我不久前才遇到这个问题,我找到了这个用于webpack的加载器https://github.com/webpack-contrib/svg-inline-loader

install it and then define it inside the module loaders 安装它,然后在模块加载器中定义它

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

A little bit late to the party, but if you don't want to (or can't cause your using something like cra ) you can also use svg-react-loader . 晚会晚了一点,但是如果您不想(或不能导致使用cra等东西),也可以使用svg-react-loader (easy to setup with cra, and without) (易于安装,无需安装)

Then change your require statement to: 然后将您的require语句更改为:

const myIcons = require.context('!svg-react-loader!./myIcons/', true, /^\\.\\/.*\\.svg$/)

So this is the correct behaviour for the loader you've chosen. 因此,这是您选择的装载程序的正确行为。 It has imported it as a base64 image. 它已将其导入为base64映像。 You can now place it in an image tag in the source. 现在,您可以将其放在源中的图像标签中。

<img src={myIcons('./location.svg')} />

If you wanted it where it will load in the SVG code itself, you'll have to find another loader. 如果您希望将其加载到SVG代码本身中,则必须找到另一个加载器。 I ran into this a while back and couldn't find one myself, however that may have changed. 我前一段时间碰到了这个,自己也找不到,但是情况可能已经改变了。 It all depends on why you actually need the full svg code itself. 这完全取决于您为什么真正需要完整的svg代码本身。

Another option, if you need the code, is to not have it as a svg file, but create a React component with the SVG code being returned. 如果需要代码,另一种选择是不要将其作为svg文件,而是使用返回的SVG代码创建一个React组件。

export default () => (
    <svg>....</svg>
)

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

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