【问题标题】:ReactJS - Webpack Uncaught Error: require is not definedReactJS - Webpack 未捕获错误:未定义要求
【发布时间】:2018-04-26 22:06:28
【问题描述】:

下面是我的 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,
  },
};

【问题讨论】:

  • 您确定通过终端/CMD 中的节点调用此文件,例如:webpack --config webpack.config.js
  • @VijayDev 我运行 npm run dev 并且浏览器是我收到该错误的地方。

标签: javascript reactjs redux react-router react-redux


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 2022-06-15
    • 2017-11-25
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多