vue3+ts+vite 引入静态资源require报错 ——解决方案

vue3中报错,导入reqire静态图片资源的时候,显示require不存在

xml 复制代码
 'require' is not defined 

发现是 在vite中不能使用require引入图片资源,因为这里的require是webpack提供的一种加载能力,由于我们使用的是Vite,因此这里必须转用 Vite提供的静态资源载入

Vite中静态资源处理

官方示例

typescript 复制代码
const imgUrl = new URL('./img.png', import.meta.url).href
document.getElementById('hero-img').src = imgUrl

简单的说 new URL 一共接收两个参数,第一个参数即图片的路径,这里就是对应require中的值,第二个参数是vite的一个全局变量,可以理解成直接写死了 import.meta.url

解决方案:

每次处理太繁琐,我们封装一个函数;在utils文件夹下require.ts,用来处理图片

typescript 复制代码
/** vite的特殊性, 需要处理图片 */
const require_ = (imgPath: string) => {
  try {
    const handlePath = imgPath.replace('@', '..')
    console.log('handlePath::', imgPath)
    return new URL(handlePath, import.meta.url).href
  } catch (error) {
    console.warn(error)
  }
}

export { require_ }

使用的时候:

typescript 复制代码
import { require_ } from '../utils/index.ts'


 {
    img: require_('@/assets/loginSwiper/slide1.webp'),
    id: 1
 },
相关推荐
陈福国6 个月前
Centos 7 安装通过yum安装google浏览器
linux·运维·centos·陈福国·rpmgoogle·rpm安装google
陈福国10 个月前
VMware部署CentOS7
centos·vmware·陈福国·centos7·陈福国运维·vmwarecentos
陈福国1 年前
解决vue项目导出当前页Table为Excel
vue.js·陈福国·陈福国前端·vue导excel·vue table excel
陈福国1 年前
Element-plus中tooltip 提示框修改宽度——解决方案
陈福国·陈福国前端·element tooltip·tooltip宽度·tooltip换行