Making a Makefile for web development

· Björn-Eric's Developer notes


I find Makefiles to be a great form of documentation, and adding help for the targets makes them even greater.

TLDR; Provide help messages for Make targets using target_name: ## This is the help message. Then just run make to get a good overview of the project.

 1# V A R I A B L E S #
 2COLOR_RESET   = \033[0m
 3COLOR_INFO    = \033[32m
 4COLOR_COMMENT = \033[33m
 5
 6# T A R G E T S #
 7default: help
 8
 9help: ## Display this help message
10	@printf "${COLOR_COMMENT}Usage:${COLOR_RESET}\n"
11	@printf " make [target]\n\n"
12	@printf "${COLOR_COMMENT}Available targets:${COLOR_RESET}\n"
13	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; { \
14		printf " ${COLOR_INFO}%-30s${COLOR_RESET} %s\n", $$1, $$2 \
15	}'
16
17####
18
19up: ## Start Docker development environment
20	docker compose up -d
21	open http://localhost:8000
22
23down: ## Docker development environment
24	docker compose down
25
26clean: ## Clean /dist, /preview and Docker container
27	rm -r ./preview ./dist || true
28	docker compose rm -sf
29
30build: install ## Build Plugin
31	yarn build
32
33dev: ## Hotreloaded preview of standalone Svelte app
34	yarn dev
35
36install: ## Install dependencies
37	yarn install
38
39version: ## Display package version
40	@cat package.json | jq .version

This example file comes from a Svelte project that get containerized on Gitlab. We can either run it with Yarn on Docker. The important stuff here is lines 13-15 - setting up the color variables and the help target.

Explanations #

The help target #

The somewhat unreadable lines 13-15 does in simpler terms does this:

We can now annotate our targets with a ## to provide a help message for that target!

This is used quite a lot in the wild.

Some notes on the Makefile syntax #

Prefixing a command with @ will run, but now print the command. Targets can depend on other targets by listing them after the : (and before the ## in our case).

Make can "chain" multiple targets after one another so running make clean up will run the targets run and up consecutively.


Home