Hot Module Reloading with Webpacker
It is time to give a boost to frontend development in Rails
If you read my previous article on how to switch from Sprockets to Webpacker, you can now start taking advantage of the features Webpack offers. One of the most interesting is Hot Module Reloading, supported out-of-the-box in Webpacker.
By default, Webpacker enables Hot Live Reload, that reloads pages when the resources change.
Just run bin/webpack-dev-server
and at every javascript or stylesheet change, the page will be reloaded.
This is a cool feature but we can do a step forward: by using Chrome Devtools Workspaces, and configuring your source maps in a proper way, you can edit them directly in the browser.
Edit source files in your browser
Change the development configuration of webpacker as follows and restart bin/webpack-dev-server:
# config/webpack/development.rbprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';
const environment = require('./environment');
if (!module.hot) {
environment.loaders.get('sass').use.find(item => item.loader === 'sass-loader').options.sourceMapContents = false;
}
module.exports = environment.toWebpackConfig();
This will generate source maps without the original source file inside them, allowing us to link it directly in the browser. Check the following video:
Pretty awesome, right? Now you can edit your style directly in the browser.
This way of working with stylesheets can be improved further, avoiding the full reload of the page, and by refreshing only the stylesheets upon change: is called Hot Module Reloading
In order to do so, we need to activate it in webpacker.yml
.
# config/webpacker.yml[...]
development:
dev_server:
hmr: true
[...]
[...]
and not import the stylesheets via stylesheet_pack_tag since they will be included from packs/application.js
. To recap:
# packs/application.js
import './stylesheets'
and
# app/views/layouts/application.html.erb<%= stylesheet_pack_tag 'stylesheets', 'data-turbolinks-track': 'reload' unless Webpacker.dev_server.hot_module_replacing? %>
Note that you will need to restart also the Rails server everytime you change the hmr
option, since Webpacker.dev_server.hot_module_replacing?
is evaluated during the server startup.
Thanks to that you will now have Hot Module Reloading and you can really give a boost to your frontend development with Rails! 🎉
Interested in proceeding and take a look at how you can use HMR for the Javascript part of your code? Read my article about HMR with React and Rails.