Skip to content

Instantly share code, notes, and snippets.

@kylecordes
Created May 28, 2020 16:20
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 kylecordes/b0427bbe6a1f201b016c9bf06161749e to your computer and use it in GitHub Desktop.
Save kylecordes/b0427bbe6a1f201b016c9bf06161749e to your computer and use it in GitHub Desktop.
Post process Scully output to insert top level script tags
// Post-process Scully output to insert top-level third party script tags.
const globby = require('globby');
const fs = require('fs');
const path = require('path');
const myArgs = process.argv.slice(2);
if (myArgs.length !== 2) {
console.error('Usage: <distDir> <fragmentFile>');
console.error(
'Fragment will be inserted at the start of the <body> in each index.html'
);
process.exit(1);
}
const [distDir, fragmentFile] = myArgs;
const htmls = globby.sync(path.join(distDir, '**/index.html'));
const utf8 = { encoding: 'UTF-8' };
const fragment = fs.readFileSync(fragmentFile, utf8);
htmls.forEach(fn => {
const contents = fs.readFileSync(fn, utf8);
const fixed = contents.replace(/<body.*>/, match => match + fragment);
fs.writeFileSync(fn, fixed, utf8);
});
@SanderElias
Copy link

Why don't you use a render-plugin for this?
Something like this:

const injectFragment = (html: string) => {
  const { fragment } = getMyConfig(injectFragment);
  return html.replace(/<body.*>/, match => match + fragment);
};

/** set a default config */
setMyConfig(injectFragment, {
  fragment: `<script>console.log('you forgot to configure a fragment')</script>`
});

registerPlugin('render', 'injectFragment', injectFragment);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment