Created
October 2, 2022 17:54
-
-
Save ayyash/7f1109ad7e9bd54f1a76942b2ca57271 to your computer and use it in GitHub Desktop.
The PreRender worker function
This file contains 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
export async function PreRender({ | |
indexFile, | |
clientPath, | |
serverBundlePath, | |
route, | |
}: RenderOptions): Promise<RenderResult> { | |
const result = {} as RenderResult; | |
// this is the index.html | |
const browserIndexOutputPath = path.join(clientPath, indexFile); | |
// correct route folder | |
const outputFolderPath = path.join(clientPath, route); | |
// add route/index.html | |
const outputIndexPath = path.join(outputFolderPath, 'index.html'); | |
// read index file | |
let indexHtml = await fs.promises.readFile(browserIndexOutputPath, 'utf8'); | |
// change this for critical css | |
// Workaround for https://github.com/GoogleChromeLabs/critters/issues/64 | |
indexHtml = indexHtml.replace( | |
/ media="print" onload="this\.media='all'"><noscript><link .+?><\/noscript>/g, | |
'>', | |
); | |
// now get those out of the server bundle, | |
// notice the dynamic import | |
const { renderModule, AppServerModule } = await import(serverBundlePath); | |
// run renderModule | |
let html = await renderModule(AppServerModule, { | |
document: indexHtml, | |
url: route, | |
}); | |
// inline critical css, copied as is | |
// notice the universal common tools are in the parent folder | |
// if not, you need to install it | |
const { ɵInlineCriticalCssProcessor: InlineCriticalCssProcessor } = await loadEsmModule< | |
typeof import('@nguniversal/common/tools') | |
>('@nguniversal/common/tools'); | |
const inlineCriticalCssProcessor = new InlineCriticalCssProcessor({ | |
deployUrl: '', | |
minify: true | |
}); | |
const { content, warnings, errors } = await inlineCriticalCssProcessor.process(html, { | |
outputPath: clientPath, | |
}); | |
result.errors = errors; | |
result.warnings = warnings; | |
html = content; | |
// create folder if needed, then write file to index | |
fs.mkdirSync(outputFolderPath, { recursive: true }); | |
fs.writeFileSync(outputIndexPath, html); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment