Vite + Vue3 SFC Script Setup用props传图片路径报require is not defined错误
问题根因
Vite 基于原生 ES 模块规范实现,没有内置 CommonJS 规范的 require 方法,因此原有基于 require 的动态资源引入写法直接报错。同时 ES 模块的静态 import 语法只能在代码顶层使用,不支持传入动态拼接的路径参数,因此你尝试的另外两种写法也无法正常运行。
可用解决方案
方案1:使用 new URL 动态构造资源路径(推荐)
这是 Vite 官方推荐的动态引入静态资源的方式,直接通过 import.meta.url 作为基础路径拼接资源地址即可,组件可正常复用:
<script setup> import { computed } from 'vue' const props = defineProps({ imagePath: { type: String, required: true }, }) // 动态拼接资源路径 const imgSrc = computed(() => new URL(`/src/assets/${props.imagePath}`, import.meta.url).href) // 如果配置了 @ 别名指向 src 目录,也可以写成 new URL(`@/assets/${props.imagePath}`, import.meta.url).href </script> <template> <img :src="imgSrc" /> </template>
如果使用 @ 别名,需要确保你的 vite.config.js 中已经完成别名配置,参考配置如下:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': path.resolve(__dirname, 'src') } } })
方案2:使用 import.meta.glob 批量预引入资源
如果你的图片都放在固定目录下,也可以提前批量引入目录下所有资源,再根据 props 匹配对应地址:
<script setup> import { computed } from 'vue' const props = defineProps({ imagePath: { type: String, required: true }, }) // 批量引入 assets 目录下所有 png 格式图片,可按需修改匹配规则 const imgModules = import.meta.glob('@/assets/*.png', { eager: true }) const imgSrc = computed(() => imgModules[`/src/assets/${props.imagePath}`].default) </script> <template> <img :src="imgSrc" /> </template>
注意事项
- 生产构建时 Vite 会自动处理上述路径引入的静态资源,正确生成哈希文件名并替换路径,无需额外配置
- 如果是小于 4kb 的图片,Vite 会自动转成 base64 内联,符合静态资源优化的常规逻辑
内容的提问来源于stack exchange,提问作者Dony
相关产品推荐
相关产品推荐

