Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@SanderElias SanderElias commented May 29, 2020

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
You can’t perform that action at this time.