How To Use Loaded Svg Module
Solution 1:
If you're using require on a svg file, then the variable will be a string like <svg>...</svg>
. In the case of simple html, you could just add that with string interpolation. Might work with JSX as well.
Solution 2:
For some reason, the alternate type file for other extensions didn't seem to work for me. Instead, what I've found (with a fairly brand-spankin'-new CRA repo) was just change it to look roughly like the following:
const { default: logo } = require('./logo.svg') as { default: string };
It's not a great situation there, but you could potentially wrap requiring other assets by doing something like:
functionrequireAsset(src: string): { default: string } {
returnrequire(src);
}
The only drawback that I can see is that you'll get annoying warnings that I can't find a way to suppress. The reason for that is that it's a warning straight from webpack, so though it will say to try to use // eslint-disable-next-line
, it will not work. If there are no other warnings or errors, then you should be fine with the assets specifically.
Update 1
Looking into an issue surrounding the warning I mentioned above, the reason for the warning might stem from the fact that webpack doesn't know how to resolve a dynamic asset like that, which might mean that it pulls in more than it should. If you need to suppress the warning further, it is possible by putting an interpolated string with the parameter in it, though I'd not be surprised if webpack would then detect when this is being done and result in the same warning. One of the suggestions from the maintainers is to add some specificity as to what file it might require, such as hard-coding a specific path. You could potentially add a folder such as assets
with the logo in it and refactor the wrapper function to point to that folder:
functionrequireAsset(src: string): { default: string} {
returnrequire(`./assets/${src}`);
}
The above code would restrict the included assets to just the assets
folder and any subdirectories.
The problem as I see it is that any of these workarounds aren't really that great because it might start to mess with the dependency resolution with webpack and that could be problematic. The better option (if it works) would be to have that assets.d.ts
file that's included in the tsconfig.json
and as mentioned in the related question.
Post a Comment for "How To Use Loaded Svg Module"