Vite/Vue 3: "Undefined requirement" when using image source as prop
P粉301523298
P粉301523298 2024-04-06 09:50:25
0
1
477

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粉301523298
P粉301523298

reply all(1)
P粉262926195

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

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

After some searching, I found this Vue 3 code example that worked for meLink


 
setup() {
  const getImageUrl = (name) => {
        return new URL(`../../lib/Carousel/assets/${name}`, import.meta.url).href
    }
  return { carouselData, getImageUrl }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template