简体   繁体   中英

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

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.

I tried to google it but I didn't find anything relevant. thanks

I just faced that issue not long ago, I found this loader for 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 . (easy to setup with cra, and without)

Then change your require statement to:

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. 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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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