In the Nuxt documentation they gave the code example below for dynamic image loading.
<img :src="require(`~/assets/img/${image}.jpg`)" />
However, when I use it I get the following error in the browser console " Require is not defined "
Answering my question as it took me a whole day of searching...
Apparently 'require()' works for Webpack only and doesn't work with Vite .
And as Nuxt3 comes by default with Vite it wasn't working with me.
So to there are 2 options for fixing this issue:
Change from Vite to Webpack.
Use the code below instead of what's described in the Nuxt documentation to import dynamic images.
// in HTML
<img :src="getImageUrl()"/>
// in script
function getImageUrl(name) {
return new URL(`./dir/${name}.png`, import.meta.url).href
}
Useful sources :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.