Skip to main content

Pre-compress assets with Gzip and Brotli

My host doesn’t compress assets on the fly, so I pre-compress them as part of my GitHub Actions workflow.

Using find

I could just find all compressible files, and run gzip / brotli on them:

find public -type f -regextype posix-extended \
    -iregex '.*\.(css|html|js|json|mjs|svg|webmanifest|xml)' \
    -exec brotli --force --keep --output="{}.br" "{}" \;

Using make

But I love make, so I ended up with this instead:

PUBLIC_DIR := public

COMPRESSIBLE_EXTENSIONS := css html js json mjs svg webmanifest xml

COMPRESSIBLE_FIND_INCLUDE := $(subst =, ,$(subst $(eval) , -o ,$(patsubst %,-iname='*.%',$(COMPRESSIBLE_EXTENSIONS))))
COMPRESSIBLE_FILES := $(shell find $(PUBLIC_DIR) -type f \( $(COMPRESSIBLE_FIND_INCLUDE) \) 2> /dev/null)
COMPRESSIBLE_FILES_BROTLI := $(addsuffix .br, $(COMPRESSIBLE_FILES))
COMPRESSIBLE_FILES_GZIP := $(addsuffix .gz, $(COMPRESSIBLE_FILES))

.PHONY: compress
compress: compress-gzip compress-brotli

compress-gzip: $(COMPRESSIBLE_FILES_GZIP)
        @echo
        @echo "Finished compressing files with Gzip!"

compress-brotli: $(COMPRESSIBLE_FILES_BROTLI)
        @echo
        @echo "Finished compressing files with Brotli!"

$(PUBLIC_DIR)/%.gz: $(PUBLIC_DIR)/%
        @gzip -f -k $<
        @printf "."

$(PUBLIC_DIR)/%.br: $(PUBLIC_DIR)/%
        @brotli -f -o $@ $<
        @printf "."