How might I obtain a URL path to images in my project? #26
-
Hello there, I managed to set up Vite successfully, migrating away from the ever-confusing Webpacker, to work with Vue 3 on a new Rails 6 app and it's working great when bundling assets - super fast! However, I've noticed that in a particular component of mine, where I'm dynamically importing images as props, that I've had to use this ugly prefix in order to get it to display successfully in development.
I'm guessing I could probably get round this by configuring my |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi! Happy to hear that it's working well for you. Using If you only need a path to the default image, you could import it: import ecommerceImagePath from '~/images/photos/ecommerce.jpg' In development it will be the same path you wrote by hand, but it also works in production, and is less error prone since moving or deleting the image will cause the build to fail. If you need to do this for many images and don't want to import them manually, you could use const photos = import.meta.globEager('../images/photos/**/*')
const imagePath = photos['../images/photos/ecommerce.jpg'].default One downside of this approach is that you can't use aliases in the glob path, it has to be explicit. You could then use it to receive an image name, to make the external API of the component a bit nicer: const getPhotoUrl = name => photos[`../images/photos/${name}.jpg`].default
const image = computed(() => ({ 'background-image': `url("${getPhotoUrl(props.backgroundImage)}")` })) |
Beta Was this translation helpful? Give feedback.
Hi! Happy to hear that it's working well for you.
Using
@fs
paths will not work in production, so I'd recommend to avoid using them directly.If you only need a path to the default image, you could import it:
In development it will be the same path you wrote by hand, but it also works in production, and is less error prone since moving or deleting the image will cause the build to fail.
If you need to do this for many images and don't want to import them manually, you could use
import.meta.globEager
: