I’m creating a React app with Vite and my images are stored in the public folder of my app and are accessed with public/image-name or .public/image-name. When I run the code locally all of them display but when I build and try to deploy the page on GitHub or see the preview with npm run preview
all of them disappear.
It’s definitely not the path problem since I’ve checked every single possible combination of relative and absolute paths. When I import the image to react with import img1 from 'public/beagle.jpg'
, I get Failed to resolve import "public/beagle.jpg" from "src/modules/CardDiv.jsx". Does the file exist? and it clearly exists because I used it locally. When clicking on the file in VSCode GUI nothing appears, a blank page.
>Solution :
Absolute paths are not available by default, they need to be configured with a compiler like TypeScript. Don’t import assets from your public folder, those assets are exposed statically (http://example.com/beagle.jpg). Instead, put the image in the same directory you want to import from:
modules/
├─ CardDiv.jsx
├─ beagle.jpg
Then in CardDiv.jsx
:
import beagle from "./beagle.jpg";
const Component = () => <img src={beagle} />;
Note: this has nothing to do with React. This is handled by your build system in your case Rollup via Vite.
Edit: as Milan Patel pointed out, read the Vite documentation for more information about the public directory.