While working on Laravel project based on Jetstream I realised Hot Reload wouldn’t work on the default Laravel Sail docker config. I am documenting what needed to be updated to save me time when I need this again.
What Is HMR?
Hot Module Replacement (HMR) is a technique used to refresh web pages as we make changes to the code. That means you don’t need to manually refresh the page each time you make a change to see the changes. Using HMR saves time since the part of the page that got changed is refetched automatically and replaced in the DOM.
The important thing here is that HMR maintains the current state of the component in the browser (when possible) so if you had a modal opened and you only updated the CSS of that modal, it should stay open and the changes will be reflected immediately.
Update Laravel Sail for HMR
Unfortunately, Laravel Sail Docker configuration does not come with the needed HMR configuration so we need to do a couple of changes before running sail npm run hot
.
The first thing we need to do is to expose port 8080 used by Laravel Mix in our docker configuration.
services:
laravel.test:
build:
context: ./vendor/laravel/sail/runtimes/8.1
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: sail-8.1/app
extra_hosts:
- 'host.docker.internal:host-gateway'
ports:
- '${APP_PORT:-80}:80'
- '8080:8080' <--- Add this
This will expose the port 8080 from docker to our local machine and therefore our browser.
Next thing we need to do is update the webpack dev server configuration that runs inside the container to run on the same port.
const path = require('path');
module.exports = {
resolve: {
alias: {
'@': path.resolve('resources/js'),
},
},
devServer: {
host: '0.0.0.0',
port: 8080,
},
};
That’s it! Running sail npm run hot
should now work with no other changes!
Thank you very much, this helped me!