Vite / Vue 3:使用图像源作为道具时“未定义要求”

新手上路,请多包涵

我从 Vue CLI 切换到 Vite CLI ,从 Vue 3 的 Composition API 切换到 SFC Script setup API。

它以前对我有用

当我使用官方 Vue CLI 时,我可以通过 props 传递路径的文件名来导入图像源:

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

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

然后这样称呼它:

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

迁移到 Vite 后出现的错误

但是自从我迁移到 Vite CLI 后,出现了“Uncaught ReferenceError: require is not defined”的错误。我的文件现在使用脚本设置语法,如下所示:

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

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

require is not define 错误

我试过的

我已经尝试使用相对路径直接从 assets 文件夹导入文件,并且成功了。但是我无法使用 import 语句指定 props 的路径。

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

我也在模板中尝试了 import 语句,但它甚至无法编译代码:

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

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

我错过了什么吗?也许存在一个插件可以帮助我实现这一目标?

原文由 Dony 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 956
1 个回答

我也遇到了这个问题。我搜索了这个并根据这个 github问题评论 找到了,

使用 Vite 时,源代码中不应该有 require 。只有 ESM。

有关此 功能的更多信息 | Vite - 静态资源

通过一些搜索,我找到了这个对我有用的 Vue 3 代码示例 链接

<CarouselItem v-for="(item,index) of carouselData" :key="index">
 <img :src="getImageUrl(item.img_name)" />
</CarouselItem>

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

原文由 leipzy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题