I'm following a Udemy course and trying to get HMR running with webpack version 5.67.0 and webpack-dev-server 4.7.3, but it does not work. When I modify and save a CSS file, webpack re-compiles the project correctly, and the front-end updates correctly, but hot module replacement doesn't work. It does a full page reload instead. HMR was working fine until I tried to implement the before
property.
I have been down a rabbit hole for two days following different suggestions, but still it is not working.
Here is my webpack.config.js:
const path = require('path')
const postCSSPlugins = [
require('postcss-import'),
require('postcss-simple-vars'),
require('postcss-nested'),
require('autoprefixer')
]
module.exports = {
entry: './app/assets/scripts/App.js',
output: {
filename: 'bundled.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
watchFiles: ('./app/**/*.html'),
static: path.join(__dirname, 'app'),
hot: true,
port: 3000,
// liveReload: false
},
mode: 'development',
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader','css-loader', {loader: "postcss-loader", options: {postcssOptions: {plugins: postCSSPlugins}}}]
}
]
}
}
DETAILED PROBLEM DESCRIPTION:
Here are the details:
- Hot module reload was working until I tried to add the
devServer.before
property in webpack.config.js
devServer property:
devServer: {
before: function(app, server) {
server._watch('./app/**/*.html')
},
static: path.join(__dirname, 'app'),
hot: true,
port: 3000
},
and my App.js file:
import '../styles/styles.css';
if (module.hot) {
module.hot.accept();
}
- When I tried to add the
before
property I got the error that this property was invalid also. I found this migration guide (https://github.com/webpack/webpack-dev-server/blob/master/migration-v4.md) saying thatbefore
was replaced withonBeforeSetupMiddleware
and arguments were changed also. I tried replacing before with this:
onBeforeSetupMiddleware property:
onBeforeSetupMiddleware: function (devServer) {
devServer.app.get('./app/**/*.html', function (req, res) {
res.json({ custom: "response" });
});
},
At that point there were no more compile errors for the server, but hot reload wasn't working anymore. Whenever I changed the CSS it did a FULL PAGE RELOAD every time!
Then I spent another half hour combing the course Q&A for answers. I found one user, Simeon who said this:
For those who are using Webpack 5 and webpack-dev-server >= 4.0.0.
In webpack.config.js change before option with the following:
watchFiles: ('./app/**/*.html'),
- So, I removed onBeforeSetupMiddleware and replaced with
watchFiles
. Restarted the dev server. NO CHANGE --whenever CSS is changed it does a full page refresh now!
Help! What am I doing wrong? How can I get this fixed?
Thank you!
PS: If it helps, here's my GitHub repo where you can see my all my code: