导航菜单
首页 >  NextJS Build fails with Module not found webpack Issue  > SVGR fails to load SVGs with Next 11 · Issue #26130 · vercel/next.js · GitHub

SVGR fails to load SVGs with Next 11 · Issue #26130 · vercel/next.js · GitHub

I thought a lot about this change. First I was frustrated, then I reflected on how I am using SVGs. I've also been utilising SVGR to inline my SVGs. But only to be able to re-color and modify a few SVG attributes.

It actually makes sense to me not to inline SVGs if these are my requirements. But so far I had not thought about a different approach. Asking Google, it turned out it'd be an option to leverage the tag in combination with the src attribute that comes with StaticImageData. However, this requires all SVGs to have a unique id as in the following snippet:

// MySvg.svg// then use it later when imported through `next-image-loader`import {src} from './MySvg.svg'

That was not the case for my assets.

Therefore I experimented with a few webpack loaders. I tried svg-as-symbol-loader and string-replace-loader. The former had to be modified, the latter only allowed a simple string replacement, which can easily fail or be insufficient.

However, the experiment turned out to solve my issue AND my SVGs can now be cached properly while still being able to use my SVG attributes as before. I also don't have to use an img tag, which I see as a less flexible alternative as we cannot style the svg any longer.

I went a step further and created a custom loader that is a bit smarter than those I tried before. You can find it here together with some docs that further describe its usage and implementation:

https://www.npmjs.com/package/svgid-loader

All it does is to add an id attribute to the first svg element it finds. Take a look at the sources here and leave your feedback.

Might not be a solution for everyone, but I actually will stick with it from now on as it also reduces markup, enables caching and complies with how nextjs loads such assets.

相关推荐: