Replacing the hot module

This is one of the most useful features provided by webpack. Although our project is already configured and enabled with this feature, in this section we are going to walk through it. We are using webpack-hot-middleware as it allows us to add hot reloading into an existing server (https://github.com/webpack-contrib/webpack-hot-middleware). To configure it, follow these steps:

  1. Install the npm module:
yarn add webpack-hot-middleware --dev --exact
or
npm install --save-dev webpack-hot-middleware
  1. Enable hot reloading in the webpack configuration file. If you check the webpack/webpack.dev.babel.js file, you will see the configuration inside the plugins array:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
inject: true,
template: 'app/index.html',
}),
new CircularDependencyPlugin({
exclude: /a.js|node_modules/,
failOnError: false,
}),
],
  1. Add webpack-hot-middleware/client into the entry array in the same webpack configuration file: 
entry: [
require.resolve('react-app-polyfill/ie11'),
'webpack-hot-middleware/client?reload=true',
path.join(process.cwd(), 'app/app.js'),
],
  1. Add webpack-dev-middleware to the server. Open CH07/server/middlewares/addDevMiddlewares.js:
const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

function createWebpackMiddleware(compiler, publicPath) {
return webpackDevMiddleware(compiler, {
logLevel: 'warn',
publicPath,
silent: true,
stats: 'errors-only',
});
}

module.exports = function addDevMiddlewares(app, webpackConfig) {
const compiler = webpack(webpackConfig);
const middleware = createWebpackMiddleware(
compiler,
webpackConfig.output.publicPath,
);

app.use(middleware);
app.use(webpackHotMiddleware(compiler));

const fs = middleware.fileSystem;

app.get('*', (req, res) => {
fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
if (err) {
res.sendStatus(404);
} else {
res.send(file.toString());
}
});
});
};

That should be all. Now you know how replacing the hot module really works in our application. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset