Minimizing boilerplate with NPM & Makefiles
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: https://github.com/tj/react-fatigue-dev.
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:
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
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.