- Intro
- 1. Public folder
- 2. Import files individually
- 3. Import images with import.meta.url
- 4. Using dynamic images from an API
- 5. Dynamic inline background images
- Conclusion
- Source
Intro
You’ve basically got 3 different ways to do it. Put images in the public folder and reference them normally (just a forward slash and the image name). Import images directly into your view/project and use them in your template. Use the native ESM import.meta.url
to assign images to variables, or create a function to use multiple images more easily. I’ll follow up at the end about referencing images from an API.
1. Public folder
The simplest solution is to put your assets into the public folder, and then reference them as you normally would.
1 | // add circle.svg to the public directory |
2. Import files individually
You can import each image you need as a variable that can then be referenced where you need it. The obvious drawback to this is if you have multiple images.
1 | <script setup> |
3. Import images with import.meta.url
import.meta.url is a native ESM feature that exposes the current module’s URL. Combining it with the native URL constructor, we can obtain the full, resolved URL of a static asset using relative path from a JavaScript module:
More on this from the Vite docs here.
- Similar to example #2, you assign your image path to a constant and then use it in your template. Be aware you have to write out the entire path to the file i.e.
./assets/img.png
:
1 | <script setup> |
- Dynamically import images using a function and template literals
I’ve found this to be the most useful approach, especially with multiple images.
Be aware, in the Vite docs, the ./dir/
part of the path is a placeholder — update it to the path and folder of your project.
1 | // from the docs |
- You can also define a second parameter in the function so the image extension can be dynamic as well i.e.
.jpg
,.png
,.svg
etc.
1 | <script setup> |
4. Using dynamic images from an API
Using images from an API doesn’t require any special treatment outside of normal data rendering in Vue. Just make your API request, get your data, and render it in the template.
1 | <script setup> |
5. Dynamic inline background images
I’ll add a little extra section here to quickly run over using dynamic background images with inline style tags. I’ll use the same function approach as in example #3.3, but use it inline.
1 | <script setup> |
Conclusion
Using images with Vite and Vue seemed like a head scratcher initially. I still don’t fully understand why it’s so counterintuitive when referencing local and/or dynamic assets. But hopefully this gives you a better idea. Again, I found the approach of using a function with dynamic file name and extension parameters to work best for multiple images with different formats. Be sure to check out the Vite docs for more info.
Source
https://medium.com/@andrewmasonmedia/how-to-use-images-with-vite-and-vue-937307a150c0