Skip to content

Instantly share code, notes, and snippets.

@vincentriemer
Last active December 7, 2018 01:52
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 vincentriemer/f03fa0f9c56a4ad6f4a382a8e88002b0 to your computer and use it in GitHub Desktop.
Save vincentriemer/f03fa0f9c56a4ad6f4a382a8e88002b0 to your computer and use it in GitHub Desktop.
rollup-plugin-netlify-modulepreload
import * as path from "path";
import * as fs from "fs";
export default function netlifyModulePreload(config) {
return {
name: "netlify-modulepreload",
generateBundle(outputOptions, bundle) {
const { publicRoot, entries } = config;
const { dir, format } = outputOptions;
if (format !== "es") return;
const rootPath = path.resolve("/", path.relative(publicRoot, dir));
const paths = Object.keys(entries);
const pathsObj = paths.reduce((acc, cur) => {
const pathsObj = entries[cur].reduce(
(a, c) => ({ ...a, [c]: new Set() }),
{}
);
return { ...acc, ...pathsObj };
}, {});
Object.keys(bundle)
.filter(bn => paths.some(p => bn.includes(p)))
.forEach(target => {
const files = [target, ...bundle[target].imports];
const name = target.split(".")[0];
entries[name].forEach(path => {
files.forEach(file => {
pathsObj[path].add(file);
});
});
});
const entryFiles = pathsObj["*"];
Object.keys(pathsObj).forEach(path => {
if (path === "*") return;
entryFiles.forEach(file => {
pathsObj[path].add(file);
});
});
delete pathsObj["*"];
const outputLines = [];
Object.keys(pathsObj).forEach(url => {
outputLines.push(url);
const files = [...pathsObj[url]];
files.forEach(file => {
const resolvedFile = path.resolve(rootPath, file);
outputLines.push(`\tLink: <${resolvedFile}>; rel=modulepreload`);
});
outputLines.push("");
});
fs.writeFileSync(
path.resolve(__dirname, publicRoot, "_headers"),
outputLines.join("\n"),
{ encoding: "utf8" }
);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment