Problem description

We used Wepack-dev-middleware + webpack-hot-middleware to implement hot-refresh local servers for development-time debugging. Follow the webpack-hot-plugin instructions (Add ‘webpack-hot-middleware/client’ into the entry array) to Add a string to the webpack configuration item: HotMiddlewareScript:

const hotMiddlewareScript = 'webpack-hot-middleware/client? path=/__webpack_hmr&timeout=20000&reload=true';
webpackConfig.entry.push(hotMiddlewareScript);
Copy the code
  • Reason for adding hotMiddlewareScript

The purpose of adding this line is to configure the client. According to the documentation: The addition of this string will enable the client to connect to the server (i.e. our customized dev-server), and receive the relevant notification (bundle change information) when the bundle is rebuilt. In this way, the corresponding bundle of the client will be updated to achieve hot refresh.

  • The problem

But because to take care of multiple page configurations, our entry configuration is an object, as follows:

entry: {
    main: [path.resolve(SRC_PATH, 'index.js')]}Copy the code

There is no way to use the push function to add the strings required by the Wepback-hot-plugin directly to the entry, so how do you add hotMiddlewareScript when the entry is an object (multi-page configuration)?

The solution

  1. In webpack.com, mon. Config. In js:
Entry: {// Here we can configure multiple entries to match multiple pages main: [path.resolve(SRC_PATH,'index.js')],
    sub: [path.resolve(SRC_PATH, 'sub/index.js')]},Copy the code
  1. In dev-server, a custom local development server:
const webpackConfig = require('./webpack.dev.config.js'); . const hotMiddlewareScript ='webpack-hot-middleware/client? path=/__webpack_hmr&timeout=20000&reload=true'; // The hotMiddlewareScript is appended to the end of each chunk array by iterating through the entryfor (let key of Object.keys(webpackConfig.entry)) {
  webpackConfig.entry[key].push(hotMiddlewareScript);
}
Copy the code
  1. Start the local service: NPM start
// package.json
"start": "npx cross-env NODE_ENV=development node ./build/devServer.js"
Copy the code

solution

  1. The first is to check the official website
  2. Then you can search online for relevant problems
  3. Then look at the source code, in this case read some of the webpack-hot-middleware source code to find a solution