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