I have a component that takes in an :itemName and spits out an html bundle containing an image. The image is different for each bundle.
Here\'s what I have:
Stumbled onto this issue - I initially had the "Accepted answer", but i caused http request for each and every svg, which triggered a rate limit. So I ended up with a combination the accepted answer and what @karthik proposed - using a loader in the request.context
As of CRA 2.0 @svgr is included to import svg's as react components.
const reqSvgs = require.context('!@svgr/webpack!flag-icon-css/flags/4x3', true, /\.svg$/)
So here we combine an svg loader and require.context
const flagMap = reqSvgs.keys().reduce((images, path) => {
const key = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'))
images[key] = reqSvgs(path).default
return images
}, {})
Then we map all these into a json object so we can use key lookup
To render svg's in jsx:
const Flag = flagMap['dk']
return (
)
And happy days, svgs included in bundle and no individual http requests