Vue 3 Vite - Real-time updated image links
P粉511749537
P粉511749537 2023-08-27 22:32:33
0
1
544
<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>
P粉511749537
P粉511749537

reply all(1)
P粉310931198

2022 Update: Vite 3.0.9 Vue 3.2.38

Solution for dynamic src binding:

1. Use static URL

<script setup>
import imageUrl from '@/assets/images/logo.svg' // => or relative path
</script>

<template>
  <img :src="imageUrl" alt="img" />
</template>

2. Using Dynamic URLs and Relative Paths

<script setup>
const imageUrl = new URL(`./dir/${name}.png`, import.meta.url).href
</script>

<template>
  <img :src="imageUrl" alt="img" />
</template>

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

<script setup>
const imageUrl = new URL('/src/assets/images/logo.svg', import.meta.url)
</script>

<template>
  <img :src="imageUrl" alt="img" />
</template>


2022 Answer: Quick 2.8.6 Vue 3.2.31

Here's what works for me on local and production builds:

<script setup>
const imageUrl = new URL('./logo.png', import.meta.url).href
</script>

<template>
<img :src="imageUrl" />
</template>

Please note that it does not work with SSR


Vite Documentation: New URL

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template