How to use SVGR with React's 'public' folder assets?
I'm using react + vite + svgr and my svg files are located in the "public" directory. My project structure is
|
|- src
|- public
|- icons
|- svgs
|- mySvg.svg
|- vite.config.ts
|- package.json
since public is outside of the src folder I get the error:
Assets in public directory cannot be imported from JavaScript.
If you intend to import that asset, put the file in the src directory, and use /src/assets/icons/svgs/mySvg.svg instead of /public/assets/icons/svgs/mySvg.svg.
Clarification:
- The solution of converting to
imgelement with url is not good as I need to change svg properties. - The solution of changing the folder from the
publicfolder are not good in my case as I'd like to maintain the standard public folder as the folder for assets in order to receive built in supports from different libraries.
In the end, I couldn't find / get a proper solution, so I'll post my work around as the solution for future developers (in hopes someone can supply a better one or create a better one from my solution):
SVGR has CLI support features that can be used in order to create a script that will generate react component for each *.svg file in the public folder
In your package.json file add the "update-icons" script:
create template files for your generated components and index files at a folder to your liking (e.g. "src/assets/templates"):
create a shell script file named, for example "update-icons.sh", under some dedicated folder (e.g. "scripts/icons/").
In the file content add the following
Now just run "npm run update-icons" Hope this helps!