Skip to content

Instantly share code, notes, and snippets.

@kvz
Last active August 28, 2021 14:35
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kvz/79554af7f2d1b1379536 to your computer and use it in GitHub Desktop.
Save kvz/79554af7f2d1b1379536 to your computer and use it in GitHub Desktop.
The only Makefile for Node.js projects you'll ever need - https://twitter.com/kvz/status/685853830425231361
# Licensed under MIT.
# Copyright (2016) by Kevin van Zonneveld https://twitter.com/kvz
#
# This Makefile offers convience shortcuts into any Node.js project that utilizes npm scripts.
# It functions as a wrapper around the actual listed in `package.json`
# So instead of typing:
#
# $ npm script build:assets
#
# you could just as well type:
#
# $ make build-assets
#
# Notice that colons (:) are replaced by dashes (-) for Makefile compatibility.
#
# The benefits of this wrapper are that:
#
# - You get to keep the the scripts package.json, which is more portable
# (Makefiles aren't Windows friendly)
# - Offer a polite way into the project for developers coming from Unix/C-type environments
# (npm scripts is obviously very Node centric)
# - Profit from better autocomplete (make <TAB><TAB>) than npm currently offers.
# (OSX users will have to install bash-completion http://davidalger.com/development/bash-completion-on-os-x-with-brew/)
# - You won't have to duplicate logic, this Makefile automatically reflects the latest scripts that package.json has to offer
define npm_script_targets
TARGETS := $(shell node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"));}')
$$(TARGETS):
npm run $(subst -,:,$(MAKECMDGOALS))
.PHONY: $$(TARGETS)
endef
$(eval $(call npm_script_targets))
@kvz
Copy link
Author

kvz commented Jan 9, 2016

Saves us some keystrokes building Uppy 😄

Welcoming your feedback

@calthomson
Copy link

This is awesome! Thanks for sharing 😀

@kvz
Copy link
Author

kvz commented Oct 3, 2019

This is now installable via: npm i fakefile, too

@Jarvie8176
Copy link

Jarvie8176 commented Oct 15, 2020

define npm_script_targets
TARGETS := $(shell node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"));}')
$$(TARGETS):
	npm run $(shell \
            	node -e 'for (var k in require("./package.json").scripts) {console.log(k.replace(/:/g, "-"), k);}'
            		| egrep "^$(MAKECMDGOALS)\s"
            		| head -n 1
            		| awk '{print $$2}'
            	)

.PHONY: $$(TARGETS)
endef

$(eval $(call npm_script_targets))

works for npm scripts like test:ci, test:ci-before, etc. as long as there is no mix usage of colons and hyphens (e.g. having both foo:bar and foo-bar).

@kvz
Copy link
Author

kvz commented Oct 19, 2020

Thanks, adding this in 1.0!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment