Skip to content

Instantly share code, notes, and snippets.

@baldurbjarnason
Last active May 24, 2021 17:24
Show Gist options
  • Save baldurbjarnason/38d7bbe3dead829147788d9908343a5d to your computer and use it in GitHub Desktop.
Save baldurbjarnason/38d7bbe3dead829147788d9908343a5d to your computer and use it in GitHub Desktop.
# Running `make` will build the `js` target, transforming all of your .js files in `src` to es2016, saving them in `dist`
# Running `make production` will do the same but also minify the files.
js_files := $(shell find src -name "*.js" -print)
js_targets := $(addprefix dist/, $(js_files))
# target-specific esbuild flags
FLAGS := --sourcemap --target=es2016
production : FLAGS := --minify --sourcemap --target=es2016
.PHONY: js
js: $(js_targets)
.PHONY: production
production: js
dist/%.js: %.js
npx esbuild $? $(FLAGS) --outfile=$@ --format=esm --log-level=error
# `make watch` will watch for changes and only transform the .js files that change.
#
# We check for the existence of filesystem monitoring tools (inotify for linux and fswatch for linux and other platforms) and
# use the first one we find, falling back on polling. inotifywait comes with the inotify-tools package.
#
# Polling isn't nearly as bad as you'd think, though, as make is pretty efficient.
#
# fswatch is a bit idiosynchratic, logs excessively and doesn't seem to let you only listen to close_write events
# So we check for inotifywait first and prefer that over fswatch. But fswatch is really the only game in town for macOS or BSD
inotifywait := $(shell command -v inotifywait 2> /dev/null)
fswatch := $(shell command -v fswatch 2> /dev/null)
.PHONY: watch
watch:
@echo Watching for changes
ifdef inotifywait
@while true; do \
$(MAKE) -q --no-print-directory || $(MAKE) --no-print-directory; \
inotifywait -qqre close_write .; \
sleep 0.5; \
done
else ifdef fswatch
@while true; do \
$(MAKE) -q --no-print-directory || $(MAKE) --no-print-directory; \
fswatch --exclude node_modules -1r . > /dev/null; \
sleep 0.5; \
done
else
@while true; do $(MAKE) -q --no-print-directory || $(MAKE) --no-print-directory; sleep 0.5; done
endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment