reactjsnpmvitenpm-build

ReactJS, Vite Project: "npm run build" keeps missing the images inside "assets" when it creates folder "dist"


I was trying to upload my ReactJS Project on cPanel and after running "npm run build" it created a "dist" folder, i noticed that my image files weren't on the generated assets folder nor appearing with the "npm run preview".

The generated dist folder had an assets folder with my favicon, a js config file and a css file. the issue is that the fav icon was on my assets folder with the other images that weren't added to the build. the only difference is the .ico was linked on my index.html.

structure of my project on vscode the generated dist folder

my first thought was to change de path of the images, but it didnt resolve the issue. i also have opened the network dev tools to see if there was any error loading, but the name of the image files appear with 200 code.

after looking up more about vite, i tried to apply "assetsDir: 'path'," on the vite.config.js, but it also didnt work.

the npm run preview shows the fav icon and currently on the homepage the only thing missing is the images, it just has the alt atributte with the images description.


Solution

  • The assets* options are for assets emitted by Vite. These assets are files encountered by Vite during a build, that are included in the "build graph". It seems like the files in src/assets may not be in the build graph at all, and hence not emitted into the dist folder.

    You could consider including them in the build graph as necessary by importing them into your code:

    Importing Asset as URL

    Importing a static asset will return the resolved public URL when it is served:

    import imgUrl from './img.png'
    document.getElementById('hero-img').src = imgUrl
    

    For example, imgUrl will be /img.png during development, and become /assets/img.2d8efhg.png in the production build.

    This has several advantages, such as:

    Otherwise, for other situations where you can't include a file in the build graph, you can use the public directory:

    The public Directory

    If you have assets that are

    • Never referenced in source code (e.g. robots.txt)
    • Must retain the exact same file name (without hashing)
    • ...or you simply don't want to have to import an asset first just to get its URL

    Then you can place the asset in a special public directory under your project root. Assets in this directory will be served at root path / during dev, and copied to the root of the dist directory as-is.

    So if you want the assets available in production as /assets/filename.ext, you'd place the file in your project in /public/assets/filename.ext.