首页 > 解决方案 > 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,
  },
};

标签: javascriptreactjsreduxreact-routerreact-redux

解决方案


发现问题。你用过target: node。删除它以解决问题。

这指示 Webpack 编译以在类似 Node.js 的环境中使用(使用 Node.js 加载块并且不触及任何内置模块,如 fs 或 path)。并且在浏览器中运行 require 时,没有 polyfill 可用,从而报出上述错误。


推荐阅读