I am making a real-time card game using react for my front-end (which was made using CRA), and I am storing all of my cards as .svg files in a subfolder in the src folder. I have seen in other questions that for single files you could use import {ReactComponent as Image} from 'whatever.svg'
and for an entire folder to use require.context()
. While the import statement works, the require.context method just provides me with /static/media/whatever.randomStuff.svg
files that I can only import by making an http(s) request to that location on the site. I have tried using @svgr/webpack
in the require.context function, but even when installed manually, it gives me the same output. Is there a way for me to use the import statement or something else to import all of the .svg files in that folder as ReactComponents in the file instead of having to make an http(s) request?
Asked
Active
Viewed 242 times
0

SwampyX
- 112
- 6
-
does this answer your question? https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard – keikai Dec 17 '21 at 05:48
-
no. I was hoping to not have to explicitly name each svg file explicitly. – SwampyX Dec 17 '21 at 12:16
1 Answers
0
The answer I was looking for was in this answer from another question. One thing I didn't know at the time of posting was that the version of webpack that react-scripts was using (v4.44.2) already had @svgr/webpack
, so manually installing it with npm was essentially useless because it was probably already using it to generate the /static/media/fileName.randomStuff.svg
files in the first place. In the end I used an intermediate file in the svg folder and did this:
interface CardCache {
[key: string]: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
}
const cache: CardCache = {};
/* eslint import/no-webpack-loader-syntax: off */
const files = require.context("!svg-react-loader?name=card!./", true, /\.svg$/);
files.keys().forEach(path => {cache[path] = files(path)});
export {cache};
I used the eslint comment because I did not want to replace react-scripts
with something like react-app-rewired
just so I could have access to the webpack.config.json
file.

SwampyX
- 112
- 6