Home  >  Q&A  >  body text

Vite/Vue 3: "Undefined requirement" when using image source as prop

I switched from Vue CLI to Vite CLI, and from Vue 3’s Composition API to SFC Script setup API.

How it worked for me before

When I use the official Vue CLI, I can import the image source by passing the filename of the path via props:

<template>
  <img :src="require(`@/assets/${imagePath}`)"/>
<template/>

<script>
export default {
  props: {
    imagePath: { type: String },
  },
  setup() {
    // ...
  }
}
<script/>

Then call it like this:

<template>
  <Image imagePath="icon.png" />
</template>

Errors encountered after migrating to Vite

But since I migrated to Vite CLI, I got the error "Uncaught ReferenceError: require is not Defined". My files now use script settings syntax like this:

<script setup>
const props = defineProps({
  imagePath: { type: String },
})
</script>

<template>
  <img :src="require(`@/assets/${props.imagePath}`)"/>
</template>

What I tried

I've tried importing the file directly from the assets folder using a relative path and it worked. But I can't specify the path of props using import statement.

<script setup>
// Works but do not use the props, so the component is not reusable
import logo from "./../assets/logo.png"
</script>

<template>
  <img :src="logo"/>
</template>
<script setup>
// Component is reusable but the import statement has illegal argument I guess
const props = defineProps({
  imagePath: { type: String },
})

import logo from `./../assets/${props.imagePath}`
</script>

<template>
  <img :src="logo"/>
</template>

I also tried the import statement in the template, but it doesn't even compile the code:

<script setup>
const props = defineProps({
  imagePath: { type: String },
})
</script>

<template>
  <img :src="import `./../assets/${props.iconPath}`" />
</template>

Did I miss something? Maybe a plugin exists that can help me achieve this?

P粉301523298P粉301523298108 days ago208

reply all(1)I'll reply

  • P粉262926195

    P粉2629261952024-04-07 09:26:33

    I also encountered this problem. I searched for this and found it based on this github issue comment,

    For more information about this, see Features | Vite - Static Resources

    After some searching, I found this Vue 3 code example that worked for meLink< /p>

    
     
    
    setup() {
      const getImageUrl = (name) => {
            return new URL(`../../lib/Carousel/assets/${name}`, import.meta.url).href
        }
      return { carouselData, getImageUrl }
    }

    reply
    0
  • Cancelreply