javascript - ReactJS - Webpack 未捕获错误:未定义要求
问题描述
下面是我的 webpack.config.js。在浏览器开发者工具中,得到“Uncaught ReferenceError: require is not defined”。
我一直在尝试解决这个问题,但仍然无法弄清楚我错过了什么..
我进行了很多搜索,但找不到适合我的案例的正确答案。
谁能帮我解决这个问题?
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
// Constant with our paths
const paths = {
DIST: path.resolve(__dirname, 'dist'),
SRC: path.resolve(__dirname, 'src'),
JS: path.resolve(__dirname, 'src/js'),
};
// Webpack configuration
module.exports = {
entry: path.join(paths.JS, 'app.js'),
output: {
path: paths.DIST,
filename: 'app.bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(paths.SRC, 'index.html'),
}),
new ExtractTextPlugin('style.bundle.css'),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
use: 'css-loader',
}),
},
{
test: /\.(png|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
target: 'node',
externals: [nodeExternals()],
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
},
devServer: {
contentBase: paths.SRC,
},
};
解决方案
发现问题。你用过target: node
。删除它以解决问题。
这指示 Webpack 编译以在类似 Node.js 的环境中使用(使用 Node.js 加载块并且不触及任何内置模块,如 fs 或 path)。并且在浏览器中运行 require 时,没有 polyfill 可用,从而报出上述错误。
推荐阅读
- html - 如何通过 $http.get() 从 .json 文件获取数据到 html 文件
- javascript - 单击按钮时更改视图
- python - Spotipy-为什么在获取保存的歌曲时有 50 首歌曲的限制?
- r - 使用R中的for循环填充要列出的数据框
- python-3.x - 检查两个列表中的用户名
- hyper-v - 有什么方法可以在 Windows 的 VT-x 上运行 Docker?
- java - 如何从 Java 调用 tabula (JAR)?
- spring - Spring Boot Actuator 在一个请求中返回所有指标
- javascript - 构造函数不返回方法
- spring-boot - Spring boot2,Mysql UTF-8 编码不起作用