Hot Module Reloading with Webpacker

It is time to give a boost to frontend development in Rails

Alessandro Rodi
Ruby Inside
3 min readMay 16, 2018

--

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:

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.

and not import the stylesheets via stylesheet_pack_tag since they will be included from packs/application.js. To recap:

and

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.

--

--

Alessandro Rodi
Ruby Inside

Open Source Software Engineer at Renuo AG. Located in Zürich. I do stuff. Sometimes.