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?
Last active
August 15, 2021 11:13
-
-
Save JoshuaGrams/0dfab883d780f307f4a07c475566ed3a to your computer and use it in GitHub Desktop.
Bundle javascript inline into html files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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