Skip to content

Import images using a dynamically interpolated name #65

Answered by ElMassimo
tomocrafter asked this question in Q&A

You must be logged in to vote

As @nyrf suggested, the way to achieve that in Vite is by using import.meta.glob or import.meta.globEager.

// 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.

Replies: 2 comments

You must be logged in to vote
0 replies

You must be logged in to vote
0 replies
Answer selected by ElMassimo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants