Vue 3 Vite - Real-time updated image links
P粉511749537
2023-08-27 22:32:33
<p>I'm using Vue 3 and Vite. After building production in Vite, I ran into an issue with dynamic img src. There is no problem with static img src. </p>
<pre class="brush:php;toolbar:false;"><img src="/src/assets/images/my-image.png" alt="Image" class="logo"/>< ;/pre>
<p>It works fine in both cases: when running in development mode and after a vite build. But I have some image names stored in a dynamically loaded database (menu icons). In this case I have to write the path like this: </p>
<pre class="brush:php;toolbar:false;"><img :src="'/src/assets/images/' menuItem.iconSource" /></pre>
<p> (menuItem.iconSource contains the name of the image, such as "my-image.png").
In this case it works when running the application in development mode but not after a production build. When Vite builds the application for production, the path changes (all assets are placed into the <code>_assets</code> folder). Static image sources are processed by the Vite build and the paths will be changed accordingly, but composite image sources are not. It just takes <code>/src/assets/images/</code> as a constant and does not change it (when the application throws 404 not found for image /src/assets/images/my-image.png , I can see it in network monitor)).
I'm trying to find a solution and someone suggested using <code>require()</code> but I'm not sure if vite can use it. </p>
2022 Update: Vite 3.0.9 Vue 3.2.38
Solution for dynamic src binding:
1. Use static URL
2. Using Dynamic URLs and Relative Paths
3.Have dynamic URLs and absolutepaths
Due to aggregation limitations, all imports must start relative to the import file and should not start with a variable.
You must replace the alias
@/
with/src
2022 Answer: Quick 2.8.6 Vue 3.2.31
Here's what works for me on local and production builds:
Please note that it does not work with SSR
Vite Documentation: New URL