YMH
YMH

Reputation: 3133

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"

Upvotes: 1

Views: 1282

Answers (2)

Mohamed Momen
Mohamed Momen

Reputation: 21

Previous answers not working for SSR.

An alternative is to use Dynamic Imports

Here's an example:

<template>
    <img :src="icon" alt="" />
</template>

<script setup lang="ts">
async function resolveImage(name: string) {
  const module = await import(`~/assets/images/${name}`);
  return module.default;
}
const icon = await resolveImage();
</script>

References:

Upvotes: 2

YMH
YMH

Reputation: 3133

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:

Upvotes: 4

Related Questions