Import images using a dynamically interpolated name #65
-
I want to use images on component dynamically (which is filename of image file is not sure until the component mounted.) PS. If I import it by Thank you! (I'm sorry if my English is wrong, Please feel free to ask me if any details needed.) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think you can submit a demo repo. you can look at https://vitejs.dev/guide/assets.html#explicit-url-imports or try |
Beta Was this translation helpful? Give feedback.
-
As @nyrf suggested, the way to achieve that in Vite is by using // app/frontend/utils/images.js
const images = import.meta.globEager('../assets/images/**/*')
export function getImageUrl (name) {
const importModule = images[`../assets/images/${name}.jpg`]
if (!importModule) throw new Error(`No image available for ${name}`)
return importModule.default
} Please see this related discussion where I describe a similar usage in more detail. |
Beta Was this translation helpful? Give feedback.
As @nyrf suggested, the way to achieve that in Vite is by using
import.meta.glob
orimport.meta.globEager
.Please see this related discussion where I describe a similar usage in more detail.