D3 + JavaScript Tooling's Not (Just) For Unicorns

A horrible introduction to using modern JavaScript tooling with D3

Chapter 14

Hot Module Replacement

To check out what Parcel can do, let’s start by changing our HTML to have a little headline in it…

…and then switch back to our webpage.

WAIT A SECOND. You didn’t refresh, but it changed?. What?!

Maybe we were hallucenating, and just forgot we clicked refresh? Let’s try changing our HTML a little more by adding a style section up top.

Okay, this time we’re sure about what happened. It magically auto-refreshes! That’s fun! We could get used to this, ’eh?

This is called hot module replacement, and it’s 🔥🔥🔥. Parcel detects which files change and then automatically refreshes just that part of the page.

Let’s try it with the JavaScript, and adjust the color of the circles in your graph.js file.

Uh, wait, what? Are we seeing double?

Sadly, hot module replacement is a little too 🔥🔥🔥 for D3. Most of the time when you write D3 visualizations the first thing you do is add a new chart SVG to the page, then start drawing all over the SVG. With HMR, every time it tries to reload the JavaScript it adds another visualization to the page.

Sucks!

But if we want to cheat a little bit, we can add some code to our D3 that fully refreshes the page every time HMR tries to do the partial refresh. Until we become really fancy at D3 it’s the best we’re going to have!

Add this up at the top of your graph.js:

And now every change to your D3 code will trigger a whole page refresh.

Note: Hot module replacement is mostly focused on things like React and Vue, where the page is made up of, uh, modules.

The strange thing about JavaScript build tools is that the more you use them, the more you have to change your code to adapt to them. It’s kind of irritating, but hey, so is everything else in life!