【问题标题】:React and Webpack: "Uncaught ReferenceError: require is not defined"React 和 Webpack:“未捕获的 ReferenceError:未定义要求”
【发布时间】:2021-07-11 19:40:53
【问题描述】:

我正在尝试将我的 Webpack (5.42.0) webpack.config.js 从使用 require() (CommonJS) 改写为使用 import from (ESM)。但是每当我尝试加载我的页面时,我都会得到:

Uncaught ReferenceError: require is not defined
    at Module../some/path/file.js (login.bundle.js:10731)
    at Module.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Module../some/path/util.js (login.bundle.js:10564)
    at Module.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Module../some/path/module/Module.jsx (OtherFile.jsx:37)
    at Module.options.factory (react refresh:6)

我无法弄清楚导致此错误的原因。 Webpack 设置中有很多移动部件,但我猜require 未添加到包中的原因可能是因为 Babel 配置问题?

我正在使用热模块替换、各种插件(Terser 等)。下面添加了package.jsonwebpack.config.js 的摘录。我认为所有相关行都包括在内:

// package.json excerpt:
{
  "type": "module",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
}
// webpack.config.js excerpt:
import path from 'path';
import webpack from 'webpack';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';

const config = () => {
  return {
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          loader: 'babel-loader',
          options: {
            presets: ['@babel/env', '@babel/react'],
            plugins: ['react-refresh/babel'],
          },
          resolve: {
            fullySpecified: false,
          }
        },
      ],
    },
    entry: {
      main: [
        `webpack-dev-server/client?http://localhost:3500/`,
        './app/App.jsx',
      ],
    },
    output: {
      filename: '[name]/[name].bundle.js',
      path: path.resolve(__dirname, 'backend/path/bundles'),
      publicPath: 'http://localhost:3500/',
    },
    // …etc…
  };
};

【问题讨论】:

    标签: javascript webpack commonjs babel-loader es6-modules


    【解决方案1】:

    这是否回答了您的问题:How can I use ES6 in webpack.config.js?

    长话短说,webpack.config.js 是用 Node 解析的,默认不支持 es6。你可以重命名你的配置文件webpack.config.babel.js

    话虽如此,在这样的文件中使用导入语法并不重要,require 对我来说看起来不错。

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2016-03-29
      • 2017-11-25
      • 2020-05-16
      • 2012-12-16
      相关资源
      最近更新 更多