Alexander Gromnitsky's Blog

Automatic static assets dependency discovery

Latest update:

In the past when I wanted to grab static files from node_modules directory I'd script it in a makefile like this:

vendor.src := foo/bar.js foo/bar.css
vendor.dest := $(addprefix $(out)/vendor/, $(vendor.src))
$(out)/vendor/%: node_modules/%; $(copy)

define copy =
@mkdir -p $(dir $@)
cp $< $@
endef

Then in some index.html I'd have:

<script src="vendor/foo/bar.js"></script>

& so on. This worked fine, but required a manual sync b/w the html file & its dependencies.

Then it dawned upon me (slowpoke.webp) that the value of vendor.src variable could be discovered automatically; all we need here is a decent html parser that is usable from the command line.

We can use nokogiri or a cli for cheerio library (disclamer).

vendor.src := $(shell adieu -pe '$$("link,script").map((_,e) => $$(e).attr("href") || $$(e).attr("src")).get().filter(v => /node_modules/.test(v)).join`\n`' src/index.html)
vendor.dest := $(addprefix $(out)/, $(vendor.src))
$(out)/node_modules/%: node_modules/%; $(copy)

vendor.src doesn't look very pretty any longer but now I can edit my index.html w/o worrying about the makefile.


Tags: ойті
Authors: ag