Vue.js 中 “require is not defined“

发布于:2025-06-15 ⋅ 阅读:(20) ⋅ 点赞:(0)

解决 Vue.js 中 “require is not defined” 错误
当你在 Vue.js 项目中使用 require 时遇到 “require is not defined” 错误,这通常是因为你的项目使用了 Vue CLI 3+ 或 Vite,它们默认使用 ES 模块而不是 CommonJS 的 require 语法。

解决方案

方法 1:使用 ES 模块导入方式(推荐)

javascript

import exampleImage from '@/assets/images/example.jpg';

export default {
  data() {
    return {
      imagePath: exampleImage
    }
  }
}

方法 2:使用 public 目录(适用于不需要构建处理的静态文件)

将图片放入 public 目录

直接引用:

html

<img src="/images/example.jpg" alt="Example Image">

方法 3:配置构建工具支持 require

对于 Vue CLI 项目:
确保你的项目有 @vue/cli-service 依赖

Webpack 已经配置了支持 require

对于 Vite 项目:
Vite 默认不支持 require,你需要:

使用 import.meta.glob 或 import.meta.globEager:

javascript

const images = import.meta.glob('@/assets/images/*.{jpg,png,svg}')

// 或者动态获取
const getImage = (name) => {
  return new URL(`/src/assets/images/${name}`, import.meta.url).href
}

方法 4:动态 URL(Vite 推荐方式)

javascript

export default {
  data() {
    return {
      imagePath: new URL('../assets/images/example.jpg', import.meta.url).href
    }
  }
}

为什么会出现这个错误?

现代构建工具趋势:Vue CLI 3+ 和 Vite 默认使用原生 ES 模块

环境差异:require 是 Node.js 的 CommonJS 语法浏览器环境不支持
构建配置:如果你的项目没有正确配置 Webpack 的 require 支持

最佳实践建议

对于新项目,使用 ES 模块的 import 语法 对于动态路径,使用 Vite 的 import.meta.glob 或 new
URL() 方式 如果必须使用 require,确保你的构建工具配置正确


网站公告

今日签到

点亮在社区的每一天
去签到