I switched from Vue CLI to Vite CLI, and from Vue 3’s Composition API to SFC Script setup API.
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>
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>
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?
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