Skip to content

Instantly share code, notes, and snippets.

@mrienstra
Last active January 12, 2018 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrienstra/218c0836208af352951a663652a6d7c7 to your computer and use it in GitHub Desktop.
Save mrienstra/218c0836208af352951a663652a6d7c7 to your computer and use it in GitHub Desktop.
const replace = require('replace-in-file'); // https://www.npmjs.com/package/replace-in-file
const path = require('path');
const scriptName = path.basename(process.argv[1]);
const options = {
files: [
'out/*.html',
'out/**/*.html',
],
from: [
/<link rel="preload" href="\/_next\/[^\/]+\/[^.]+\.js" as="script"\/>/g,
/(<script.+<\/script>)(<\/div>)*<\/body><\/html>/, // optional `</div>`: appears in next.js 4.2.1 but not in 4.3.0-canary.1
],
to: [
'',
(match, p1, p2) => {
let output = `<script>
setTimeout(function(){
var insertScript = function (src, id) {
var scriptEl = document.createElement('script');
id && (scriptEl.id = id);
scriptEl.src = src;
document.body.appendChild(scriptEl);
}
`;
const scripts = p1.split('</script>');
let i, l, matches;
for (i = 0, l = scripts.length; i < l; i++) {
if (!scripts[i]) continue;
output += ` insertScript('` + scripts[i].match(/ src="([^"]+)"/)[1] + `'`;
matches = scripts[i].match(/ id="([^"]+)"/);
if (matches) {
output += `, '` + matches[1] + `'`;
}
output += `);\n`;
}
return output + `}, 0);\n</script>` + (p2 || '') + `</body></html>`;
},
],
};
replace(options)
.then(changes => {
console.log(scriptName + ': modified files:', changes.join(', '));
})
.catch(error => {
console.error(scriptName + ': error occurred:', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment