javascriptreactjsvite

Images Display on Local but Not in Production with React + Vite (Absolute Path)


I am using React, TypeScript, and Vite with the following alias configuration:

resolve: {
  alias: {  
    "~assets": resolve(__dirname, "./src/assets"),  
    "~images": resolve(__dirname, "./src/assets/img"),
  }
}

When I import images like this:

import avatar from '~images/general/user/avatar.svg';
<img src={avatar} alt="avatar" />;

It works perfectly.

However, when I try to use a dynamic path like this:

<img src={`~images/general/user/${icon}.svg`} />;

The image doesn't display at all.

My images are located in src/assets/img/general/user

OR

When I use the following image path:

<img src={`./src/assets/img/general/user/${icon}.svg`} />

It works in development mode, but not in production mode. I want to make it work in both development and production modes. Can anyone explain why this is happening and how to fix it?


Solution

  • What you are doing is passing the string to img tag.

    Vite does not process aliases from string literals like this one -> <img src={`~images/general/user/${icon}.svg`} />

    The absolute path worked in dev mode, just because it happens to be the relative path where image is actually present.

    In production, there is no image file on the path ./src/assets/img/general/user/${icon}.svg.

    import avatar from '~images/general/user/avatar.svg';
    <img src={avatar} alt="avatar" />;
    

    This is the only correct way of loading images from assets. Else you need to keep images in the public directory.