uniapp出现chunk-vendors.js:92746 uncaught referenceerror: require is not defined如何解决

在uniapp项目中运行时报错:chunk-vendors.js:92746 Uncaught ReferenceError: require is not defined,请问这是什么原因导致的?项目使用的是vue-cli脚手架,编译H5时出现的错误。已尝试配置webpack的externals和babel插件但未解决。请问该如何正确处理这种CommonJS模块引入报错问题?

2 回复

在UniApp中遇到require is not defined错误,通常是因为在代码中使用了Node.js的require语法,而UniApp环境不支持。解决方法:

  1. 使用ES6的import替代require
  2. 检查第三方库是否兼容小程序环境
  3. 确保vue.config.js中正确配置了webpack

建议检查代码中的模块引入方式,改用ES6模块语法即可解决。


这个问题是因为在 UniApp 项目中,浏览器环境中不支持 CommonJS 的 require 语法,而代码中使用了该语法导致的。以下是几种解决方案:

1. 检查并修改第三方依赖

某些第三方库可能使用了 require,在 UniApp 的浏览器环境中无法运行。解决方法:

  • 使用支持 ES6 模块(import)的库替代。
  • package.json 中检查依赖,移除或替换不兼容的库。

2. 配置 Webpack 别名

vue.config.js 中配置别名,避免引入 Node.js 模块:

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        'module-name': false // 将不兼容的模块设为 false
      }
    }
  }
}

3. 使用条件编译

如果代码需区分环境,使用条件编译:

// #ifdef H5
import module from 'module-path'
// #endif

// #ifndef H5
const module = require('module-path')
// #endif

4. 检查自定义代码

确保项目中的自定义代码没有使用 require,改用 ES6 模块:

// 错误
const utils = require('./utils.js')

// 正确
import utils from './utils.js'

5. 升级 UniApp 和依赖

确保使用最新版本的 UniApp 和相关依赖,避免已知兼容性问题。

通常通过以上方法可以解决问题。重点是确保所有代码和依赖均使用 ES6 模块语法。

回到顶部