Vue3引入图片等无法使用require怎么办?

160人浏览 / 0人评论 / 添加收藏

先说说问题现象:在前端项目中使用vue3开发项目时,使用require('图片路径'),结果浏览器报错,提示如下:
Uncaught (in promise) ReferenceError: require is not defined.

问题分析:因为require是webpack提供的一种加载能力,但是vue3项目时搭配vite的,所以这里应该用vite提供的静态资源载入方法,

官方文档:https://vitejs.cn/guide/assets.html#the-public-directory

问题解决:

两种解决方案:

1、使用 import from方式。

示例代码:

import imageIcon from '@/assets/images/insert.png';

然后在img标签上引用:

<img :src="imageIcon" />

2、使用URL方式。

将上面的require改为new URL这种格式,页面就可以正常加载静态资源了。

代码如下:
<img :src="image" />

const image = new URL('@/static/images/test.png', import.meta.url).href


 

全部评论