Assets not showing after build process in Vite and React

24 Views Asked by At

When running npm run build my pictures under src/assets/... are not available in the dist directory / production build. So not shown on the site. In dev mode it works for sure.

Any ideas on how to make them available after building?

Also, in my VSCode terminal, i get the the error that

"GET /src/assets/store2.webp" Error (404): "Not found"

    <div className="onah">
      <img src="src/assets/Deal-2.webp" 

I have attached some screenshots for a better understanding. I even had to configure my vite.configscreenshot

Screenshot2

2

There are 2 best solutions below

0
Vinicius Katata On BEST ANSWER

You should import the asset so vite could manage it and build it for production, instead of:

  <div className="onah">
     <img src="src/assets/Deal-2.webp" 

you should do:

  import deal from "src/assets/Deal-2.webp";

  <div className="onah">
    <img src={deal} ... />
0
Swapnil Ghone On

Assets in src/assets must be imported into the code to be included in the bundle. You should use it like

// Importing an image asset into the code
import image1 from './assets/image1.webp';

// Using the imported asset
<img src={image1} alt="Image 1" />

If you just want static files to be bundled with your project, you should use public/ and refer it by process.env.PUBLIC_URL

//Assuming that image is stored inside a public directory 
<img src={process.env.PUBLIC_URL+"/image1.webp"} alt="Image 1" />