Skip to content

Instantly share code, notes, and snippets.

@JoshuaGrams
Last active August 15, 2021 11:13
Show Gist options
  • Save JoshuaGrams/0dfab883d780f307f4a07c475566ed3a to your computer and use it in GitHub Desktop.
Save JoshuaGrams/0dfab883d780f307f4a07c475566ed3a to your computer and use it in GitHub Desktop.
Bundle javascript inline into html files

Put into your source directory. Run with node bundle-scripts.js on the command line. You can probably put the command into a .bat file (Windows) or .sh file (Mac OSX, Linux) so you can just double-click it to build?

const fs = require('fs')
function replaceScript(m, open, filename, rest, close) {
const script = fs.readFileSync(filename, {encoding:'utf-8'})
return open + rest + script + close
}
function replaceScripts(htmlSource) {
const script = /(<script[^>]*)\s+src="([^"]*)"([^>]*>)(<\/script>)/g
return htmlSource.replace(script, replaceScript)
}
function bundleScripts(filenameIn, filenameOut) {
const htmlIn = fs.readFileSync(filenameIn, {encoding:'utf-8'})
const htmlOut = replaceScripts(htmlIn)
fs.writeFileSync(filenameOut, htmlOut, {encoding:'utf-8'})
}
// Can call this multiple times if you need to process several html files.
bundleScripts('index.html', 'index2.html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment