简体   繁体   中英

Nuxt dynamic image - Require is not defined

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:

  1. Change from Vite to Webpack.

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM