ReactJS-Webpack报错:Uncaught ReferenceError: require is not defined求助
解决"Uncaught ReferenceError: require is not defined"的问题
从你给出的代码片段里看到用了nodeExternals,这个大概率就是问题的根源!我来给你拆解一下原因和解决办法:
核心原因
nodeExternals的作用是告诉webpack不要打包node_modules里的依赖,而是保留require()引用让Node.js环境去处理。但浏览器本身没有内置require函数,所以当你的前端代码被打包后,浏览器遇到require就会抛出这个错误。
针对性解决方案
情况1:你开发的是纯前端项目(非Electron等混合环境)
直接移除nodeExternals相关配置即可。webpack会正常把所有依赖打包进你的bundle文件里,浏览器就能识别运行了。
举个修改后的配置示例:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // 注意:webpack4+推荐用mini-css-extract-plugin替代ExtractTextPlugin const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin({ filename: 'styles.css' }) ], // 移除下面这行nodeExternals相关配置 // externals: [nodeExternals()] };
情况2:你开发的是Electron应用(渲染进程代码)
如果是Electron的渲染进程用到了node模块,不能直接依赖nodeExternals+require,推荐用以下方式:
- 在webpack配置里设置
target: 'electron-renderer' - 不要用
nodeExternals,让webpack打包渲染进程需要的依赖 - 或者通过preload脚本来访问Node.js API,这是Electron官方推荐的安全做法(避免开启
nodeIntegration带来的安全风险)
额外检查点
确认你的webpack配置里target选项是默认的web(前端项目),如果错误设置成node,webpack会输出Node.js环境的代码,同样会出现require未定义的问题。
内容的提问来源于stack exchange,提问作者Tae Hoon Lee
相关产品推荐
相关产品推荐

