简体   繁体   中英

React and Webpack: “Uncaught ReferenceError: require is not defined”

I'm trying to rewrite my Webpack (5.42.0) webpack.config.js from using require() (CommonJS) to using import from (ESM). But whenever I try to load my page, I'm getting:

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)

I cannot figure out what causes this error. There are a lot of moving parts in the Webpack setup, but I'm guessing the reason require is not added to the bundle may be because of a Babel config issue?

I'm using hot module replacement, various plugins (Terser etc.). Excerpts from package.json and webpack.config.js are added below. I think all relevant lines are included:

// 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…
  };
};

Does this answer your question: How can I use ES6 in webpack.config.js? ?

Long story short, webpack.config.js is parsed with Node, which doesn't supports es6 by default. You may rename your config file webpack.config.babel.js though.

This being said, using import syntax is of little importance in such a file, require looks good to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM