Minimizing boilerplate with NPM & Makefiles

TJ Holowaychuk
Feb 25, 2016 · 2 min read

I haven’t decided yet if I’m even going to open-source many of my components, primarily because of the pace of change they quickly become a burden.

That said, I wanted to show an example of using Makefiles in NPM to help reduce the amount of boilerplate necessary for creating React components.

Typically tasks like performing builds or starting development servers are defined in package.json as shown here:

This works fine, however if you plan on maintaining dozens of packages this can quickly become a pain. Likewise, to build a simple React component using Babel and Browserify, you’ll need a large number of dependencies:

The obvious solution for fixing the dependencies boiler is to create a meta-package which contains nothing but these dependencies, for example:

The next issue is copy/pasting “scripts” repeatedly. At this time NPM has no way to “include” scripts, and even if it could you’d lose out on some flexibility that Makefiles can provide. For my use-case I’ve also added the Makefile to this same package, it looks something like the following:

The Makefile may be included in your parent project’s Makefile with a single line:

include node_modules/react-fatigue-dev/Makefile

Note that the variables use `?=`, this lets you override the default behaviour when included, for example changing serving of “./example” to “./test” on port :8000 instead of :3000.

SERVER_FLAGS = -p 8000 test
include node_modules/react-fatigue-dev/Makefile

This technique allows you to make broad sweeping changes when the ecosystem evolves, while also reducing the boiler. I don’t suggest trying to make be-all end-all Makefiles, they would be far too complicated, but for isolated behaviour they’re much more powerful than NPM scripts.

The obvious caveat is that Make and Windows are not friends, so YMMV.


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store