Refactor build JS into a module

Stil lots of dupe code, but easily identifier and can be
cleaned up later.