First, let me clarify what I mean by “dynamic image”.
Imagine the below situations -
- You are rendering a list of products and their images. The image may be stored in local folder or coming in from S3/comparable infrastructure
- You want to change image / make image interactive. For e.g., users select fruits and the corresponding fruit image gets added in a basket
- You want to preprocess the image in some shape and form at runtime. For e.g., watermarking the image
Rendering an Image
Typically, you render images with -
This assumes that
images/apple.png exists in
public folder or available publicly.
Rendering a Dynamic Image
While providing images from a public location is great (& should be preferred), sometimes we need the images to be “processed” during build, or make it “dynamic” in some way or the other (e.g., watermarked on the go). I typically use
assets/images for images that need not be publicly exposed - but any folder should work well.
Pointing images to the
assets or some other folder is straight-forward in Nuxt2.
require works since Nuxt2 uses Webpack, which will get the import image dynamically and make it available for rendering on the page.
Nuxt3 and Vite do not work in the same way. There is more than one way to render dynamic images in Nuxt 3.
As mentioned here, you can use
glob to feed the right input to the image -
This option works, but is tiring to look at. There may also be performance issues if there are large number of images.
Note that the issue described here exists for local images. Remote images provide public URLs that can be rendered directly.
2. Use Vite require plugin
Bring the usability of Webpack
require to Vite using vite-plugin-require plugin.
Install the plugin -
vite.config.js to add the plugin -
NuxtImg) provides a helpful
You should now be able to do -
While both options work, do note that -
publicfor images that will not change. This option is easier and likely to be more performant
- Else, use one of the above options based on your use case