A horrible introduction to using modern JavaScript tooling with D3
Chapter 13
Once upon a time we had nice small, simple JavaScript files that did nice small, simple things.
But now we’re MODERN JAVASCRIPT DEVELOPERS, so we do things in horrifying, complex ways, using build tools or task runners. Build tools take our original code and do magic things to it, such as:
Overall, they take development code and turn it into production code, code that is worthy of being posted up on The Beautiful Wonderful Internet.
There are a lot of build tools out there:
but they all share one thing: they’re terrible complicated messes. Node, for some reason, loves everything to require a thousand steps and sub-packages and configuration files and oh jeez I don’t even want to think about.
What I want to do, though, is just give you a build tool that doesn’t really require configuration. So I will. It’s called Parcel, and it’s super rad and easy to use.
Let’s install it!
We’re installing Parcel globally - for every project on our machine - because it doesn’t even need to know anything about our project to work. And because it does whatever it wants.
And now we’re going to use it! Let’s add an index.html
to go with our graph.js
:
index.html
<!doctype html>
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="graph.js"></script>
</body>
</html>
graph.js
/* global d3 */
var datapoints = [
{ name: 'New York', population: 8 },
{ name: 'Los Angeles', population: 3.9 },
{ name: 'Washington, DC', population: 0.7 }
]
var svg = d3
.select('body')
.append('svg')
.attr('height', 100)
.attr('width', 400)
var xPositionScale = d3
.scaleLinear()
.domain([0, 8])
.range([0, 200])
svg
.selectAll('circle')
.data(datapoints)
.enter()
.append('circle')
.attr('r', 10)
.attr('cx', function(d) {
return xPositionScale(d.population)
})
.attr('cy', function(d, i) {
return 50
})
Now let’s run Parcel and point it at our index file.
Looks like we should go to localhost:1234, so let’s go there!
It… just looks normal, right? Nothing weird? Try viewing the source! It looks like this:
<!doctype html>
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="/graph.68ede5fa.js"></script>
</body>
</html>
Wait, what’s graph.68ede5fa.js
? I thought we had graph.js
! Let’s click graph.68ede5fa.js
to find out more about it.
What in the world is all of this code?
We didn’t write this! It’s black magic! If you search for var datapoints
, though, you can see that our code is hiding somewhere in there, along with a bunch of other stuff. A bunch of other stuff from Parcel, our build tool.
Let’s put this stuff to work!