Easiest way to reload webpack dev server when other files change
Using webpack dev server with hot module reload for your frontend is very convenient and productive. But if a file is not a dependency in webpack, it will not reload. This can be a hassle if you're editing HTML files or developing alongside a backend like Django or Laravel, and would like the page to refresh when a file changes. This can be accomplish with a just a few lines of code.
Add this to your webpack config:
// webpack config
devServer: {
before(app, server) {
const chokidar = require('chokidar');
chokidar.watch('path/to/my-files/').on('all', function (event, path) {
server.sockWrite(server.sockets, 'content-changed');
});
},
}
What does this code do?
The before()
function will be run by webpack when starting the dev server. It allows you to add your own middleware etc.
require('chokidar')
imports a file watching library used by webpack.
It is similar to nodejs fs.watch() but with some nice functionality added. You're free to use a different library if you want.
Next, we ask chokidar to watch the some files. It accepts a wide variety of inputs such as globs and arrays.
Each time a file changes, we will tell webpack that a content has changed and it will reload the page for us.
That was surprisingly easy! Yet there is almost no documentation anywhere, and even some plugins solving this problem!