Last active
December 7, 2018 01:52
-
-
Save vincentriemer/f03fa0f9c56a4ad6f4a382a8e88002b0 to your computer and use it in GitHub Desktop.
rollup-plugin-netlify-modulepreload
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
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