解决vue3 + vite + ts 中require失效的问题(require is not defind)

require is not defind因为require是属于webpack的方法,vite中找不到这个方法肯定报错

解决办法

通过vite官网了解到新的引入方式,我使用了其中一种

复制代码
imgList: [
        {
          name: "lj",
          src: new URL('../../assets/img/applyList.png', import.meta.url).href,
          title: "这是lj.png"
        },
        {
          name: "logo",
          src: new URL('../../assets/img/applyList.png', import.meta.url).href,
          title: "这是logo.png"
        },
        {
          name: "bg",
          src: new URL('../../assets/img/applyList.png', import.meta.url).href,
          title: "这是bg.png"
        },
        {
          name: "sadmas",
          src: new URL('../../assets/img/applyList.png', import.meta.url).href,
          title: "这是sadmas.png"
        }
      ]

创建一个js

创建方法:创建一个工具文件getImge.ts

复制代码
// 获取assets静态图片
export const getAssetsImge = (url: string) => {
  return new URL(`../assets/home/${url}`, import.meta.url).href
}

使用工具文件

复制代码
import { getAssetsImge } from '@/utils'

html

复制代码
          <el-avatar class="w-6 h-6" :src="getAssetsFile('user.png')" />
 
          <img class="w-6 h-6" :src="getAssetsFile('user.png')" alt="" /> 

借鉴文章:

vite+vue3中require is not defined-CSDN博客

解决vue3 + vite + ts 中require失效的问题(require is not defind)_vue3 require is not defined_夹道欢呼的博客-CSDN博客

相关推荐
是上好佳佳佳呀18 分钟前
【前端(十一)】JavaScript 语法基础笔记(多语言对比)
前端·javascript·笔记
CDN3601 小时前
排查实录:网站偶发502/504错误?360CDN回源超时配置与日志分析技巧
前端·数据库
之歆1 小时前
Day07_CSS盒子模型 · 样式继承 · 用户代理样式
前端·css
DanCheOo1 小时前
AI 应用的安全架构:Prompt 注入、数据泄露、权限边界
前端·人工智能·prompt·安全架构
We་ct2 小时前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
weixin_427771613 小时前
前端调试隐藏元素
前端
爱上好庆祝4 小时前
学习js的第五天
前端·css·学习·html·css3·js
C澒4 小时前
IntelliPro 产研协作平台:基于 AI Agent 的低代码智能化配置方案设计与实现
前端·低代码·ai编程
一袋米扛几楼984 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue
网络点点滴4 小时前
前端与后端的区别与联系
前端