React with SSR and WebpackHotMiddleware

35 views Asked by At

When I use Webpack Hot Middleware according to the document page

it always show the error, did I missing some configuration?

ReferenceError: __resourceQuery is not defined
    at Object.<anonymous> \node_modules\webpack-hot-middleware\client.js:17:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)

There is the following code:

webpack.config.js

module.exports = {
  target: 'node',
  mode: 'development',
  externals: [nodeExternals()],
  entry: ['webpack-hot-middleware/client', './server/index.js'],
  output: {
    filename: 'server.js',
    path: path.resolve(__dirname, 'build'),
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-react',
            ],
          },
        },
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ]
};

index.js

const express = require('express');
const webpack = require('webpack');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const AppServer = require('../src/AppServer').default;

const app = express();
const PORT = process.env.PORT || 3001;

const config = require('../webpack.config');
const compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('/', (req, res) => {
  const content = ReactDOMServer.renderToString(<AppServer />);
  const html = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>React SSR</title>
      </head>
      <body>
        <div id="root">${content}</div>
      </body>
    </html>
  `;

  res.send(html);
});

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

webpack with the following version "webpack": "^5.89.0", "webpack-cli": "^5.1.4", "webpack-hot-middleware": "^2.25.4", "webpack-dev-middleware": "^6.1.1",

And about entry in module.exports, it say can add param after path such as webpack-hot-middleware/client?path=/__what&timeout=2000&overlay=false but it always show the error as following

Error: Cannot find module 'webpack-hot-middleware/client?path=/__what&timeout=2000&overlay=false'
Require stack:
0

There are 0 answers