vite项目中动态引入src失败的问题解决:require is not defined

问题复现

静态引入路径(无问题)

html 复制代码
    <el-menu-item v-for="(item,index) in menuList" :index="item.name" :key="index">
      <img  class="menuItemImg" src="../svg/router/homePage.svg" alt="">
      {{ item.meta.cname }}
    </el-menu-item>

这里没啥问题。

但是,如果使用动态的路径引入,就会出问题

动态引入(图片不展示)

html 复制代码
    <el-menu-item v-for="(item,index) in menuList" :index="item.name" :key="index">
      <img  class="menuItemImg" :src="`../svg/router/homePage.svg`" alt="">
      {{ item.meta.cname }}
    </el-menu-item>

在vue中,:src需要使用require(路径)的值,而并非原始的路径值

src="静态路径"

:src="require(动态路径)"

不过这里引用之后依然有问题

require出问题(报错)

html 复制代码
    <el-menu-item v-for="(item,index) in menuList" :index="item.name" :key="index">
      <img  class="menuItemImg" :src="require(`../svg/router/homePage.svg`)" alt="">
      {{ item.meta.cname }}
    </el-menu-item>

问题分析

require在vite和webpack中,是不一样的。

在webpack环境中,我们可以随时使用require,但是在vite中,require这种引入文件的方式是不存在的,所以会报这个错误

vite路径具体可以看vite官网关于静态资源处理的模块:静态资源处理 {#static-asset-handling} | Vite中文网

(动态引入图片路径,大多数的项目都会用到,但是如果这里你不知道问题原因,那真的让人挺痛苦的。)

问题解决

封装一个require方法

javascript 复制代码
const require = (imgPath: string) => {
    try {
      const handlePath = imgPath.replace('@', '..')
      return new URL(handlePath, import.meta.url).href
    } catch (error) {
      console.warn(error)
    }
  }
   

引用

javascript 复制代码
    <el-menu-item v-for="(item,index) in menuList" :index="item.name" :key="index">
      <img  class="menuItemImg" :src="require(`../svg/router/${item.name}.svg`)" alt="">
      {{ item.meta.cname }}
    </el-menu-item>

结果

相关推荐
艾小码8 分钟前
从入门到精通:JavaScript异步编程避坑指南
前端·javascript
七度光阴;11 分钟前
Web后端登录认证(会话技术)
前端·tlias智能辅助系统
菜鸟una1 小时前
【微信小程序 + map组件】自定义地图气泡?原生气泡?如何抉择?
前端·vue.js·程序人生·微信小程序·小程序·typescript
昔人'3 小时前
`list-style-type: decimal-leading-zero;`在有序列表`<ol></ol>` 中将零添加到一位数前面
前端·javascript·html
岁月宁静8 小时前
深度定制:在 Vue 3.5 应用中集成流式 AI 写作助手的实践
前端·vue.js·人工智能
心易行者9 小时前
10天!前端用coze,后端用Trae IDE+Claude Code从0开始构建到平台上线
前端
saadiya~9 小时前
ECharts 实时数据平滑更新实践(含 WebSocket 模拟)
前端·javascript·echarts
fruge10 小时前
前端三驾马车(HTML/CSS/JS)核心概念深度解析
前端·css·html
百锦再10 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
烛阴10 小时前
Lua 模块的完整入门指南
前端·lua