Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Images do not exist even though they're in the folder

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading