At GPNL we’ve been trying to set up a Webpack development server with Hot Module Replacement (HRM) inside our local Docker development environment. If you are unfamiliar with HRM, it basically allows you to see the results of changes in your JS or SCSS files without having to refresh the browser. See the attached screen capture to get an idea.

How it works

In development, assets are server from memory and from the address http://localhost:3003/ (any available port would do) which proxies to http://www.planet4.test/. A socket listens for changes in your assets and updates the page accordingly when it detects a change. In development, no enqueueing of style files is required, these are included in the JS. What is required is an extra runtime.js file that Webpack uses to connect to the individual entries. At the moment, we use glob() to check if there are any build files. If not, the dev-files (in memory) are enqueued. This works by cleaning the build directory with CleanWebpackPlugin before building assets. This is done for both development and production scripts (see package.json and the corresponding scripts).  glob() is also used for finding the production build files as these are hashed based on their content (so you have automatic cache-busting).

Further Improvements

We needed to set variables in webpack.config.dev.js as well as a constant in functions.php. There is some duplication here and these variables should really exist as ENV-variables. Although using glob() to check if any build files exist works well, it feels a bit hacky. There is an option to create a manifest.json file with the webpack manifest plugin, which contains all files where your back-end can point to. This probably is a cleaner solution.
We have added all back-end logic to functions.php without any OOP implementation. This is something we could also improve.
One question you might have, is why a beta version of webpack-dev-server is used. This is because previous versions have a bug when working with .browserslistrc. If you have other questions, feel free to ask. You can find the code in our child theme in the ‘feature/webpack-hrm branch’: https://github.com/greenpeace/planet4-child-theme-netherlands/tree/feature/webpack-hrm. Please note it is not perfect yet, but surely this can save us a lot of time in the future!

Quick video demo