-
-
Notifications
You must be signed in to change notification settings - Fork 375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[WIP] Experimental prerenderer #1501
Closed
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
22b75cf
workling prerenderer
prateekbh 565cea0
adding html minification
prateekbh 4e278be
perf improvement for pages with huge data
prateekbh 65058b5
pooled worker thread
prateekbh fdd975d
adding an experimental flag
prateekbh 8b611f7
Merge branch 'master' of https://github.com/developit/preact-cli into…
prateekbh c5f55cf
adding in valid args list
prateekbh b55db46
fixing title
prateekbh 7b7a6c8
adding test
prateekbh 963b3ec
bug fix
prateekbh 0b746e7
Merge branch 'master' into mode-prerener
prateekbh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
const { info, warn } = require('../../util'); | ||
const { join, resolve } = require('path'); | ||
const { Worker } = require('worker_threads'); | ||
const { writeFile, mkdir } = require('../../fs'); | ||
const { PRERENDER_DATA_FILE_NAME } = require('../constants'); | ||
const pool = require('./pool'); | ||
|
||
module.exports = async function fastPrerender( | ||
{ src, dest, cwd, prerenderUrls }, | ||
stats | ||
) { | ||
let pages = [{ url: '/' }]; | ||
if (prerenderUrls) { | ||
try { | ||
let result = require(resolve(cwd, prerenderUrls)); | ||
if (typeof result.default !== 'undefined') { | ||
result = result.default(); | ||
} | ||
if (typeof result === 'function') { | ||
result = await result(); | ||
} | ||
if (typeof result === 'string') { | ||
result = JSON.parse(result); | ||
} | ||
if (result instanceof Array) { | ||
pages = result; | ||
} | ||
} catch (error) { | ||
warn('Failed to load prerenderUrls file, using default!\n'); | ||
} | ||
} | ||
|
||
// eslint-disable-next-line no-console | ||
console.log('\n\n'); | ||
info( | ||
`Prerendering ${pages.length} page${ | ||
pages.length > 0 && 's' | ||
} from ${prerenderUrls}.` | ||
); | ||
const pageData = {}; | ||
const renderedContents = await pool( | ||
pages.map(data => { | ||
pageData[data.url] = data; | ||
return { | ||
src, | ||
dest, | ||
cwd, | ||
webpack: { | ||
publicPath: stats.compilation.outputOptions.publicPath, | ||
assets: Object.keys(stats.compilation.assets), | ||
}, | ||
data, | ||
}; | ||
}), | ||
({ src, dest, cwd, webpack, data }) => { | ||
return new Promise(resolve => { | ||
const worker = new Worker(join(__dirname, 'renderer.js'), { | ||
workerData: { | ||
src, | ||
dest, | ||
cwd, | ||
webpack, | ||
data, | ||
}, | ||
}); | ||
worker.once('message', async preRenderContent => { | ||
worker.terminate(); | ||
resolve(preRenderContent); | ||
}); | ||
}); | ||
} | ||
); | ||
renderedContents.forEach(async preRenderedContent => { | ||
const dirPath = preRenderedContent.url.endsWith('.html') | ||
? preRenderedContent.url.substring( | ||
0, | ||
preRenderedContent.url.lastIndexOf('/') | ||
) | ||
: preRenderedContent.url; | ||
const filePath = preRenderedContent.url.endsWith('.html') | ||
? preRenderedContent.url | ||
: join(preRenderedContent.url, 'index.html'); | ||
await mkdir(join(dest, dirPath), { | ||
recursive: true, | ||
}); | ||
await writeFile(join(dest, filePath), preRenderedContent.content); | ||
await writeFile( | ||
join(dest, dirPath, PRERENDER_DATA_FILE_NAME), | ||
JSON.stringify(pageData[preRenderedContent.url]) | ||
); | ||
}); | ||
}; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
const { cpus } = require('os'); | ||
const resolved = Promise.resolve(); | ||
module.exports = async function pool( | ||
items, | ||
iteratorFn, | ||
concurrency = cpus().length | ||
) { | ||
const itemsLength = items.length; | ||
const returnable = []; | ||
const executing = []; | ||
for (const item of items) { | ||
const promise = resolved.then(() => iteratorFn(item, items)); | ||
returnable.push(promise); | ||
if (concurrency <= itemsLength) { | ||
const execute = promise.then(() => | ||
executing.splice(executing.indexOf(execute), 1) | ||
); | ||
executing.push(execute); | ||
if (executing.length >= concurrency) { | ||
await Promise.race(executing); | ||
} | ||
} | ||
} | ||
return Promise.all(returnable); | ||
}; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
const { isMainThread, parentPort, workerData } = require('worker_threads'); | ||
const { readFile } = require('../../fs'); | ||
const { join } = require('path'); | ||
const prerender = require('../webpack/prerender'); | ||
const ejs = require('ejs'); | ||
const { minify } = require('html-minifier'); | ||
|
||
async function render(src, dest, cwd, webpack, data) { | ||
const { url, title, ...routeData } = data; | ||
const templateSrc = await readFile(join(src, 'template.html'), 'utf-8'); | ||
const manifest = await readFile(join(dest, 'manifest.json'), 'utf-8'); | ||
const headEndTemplate = await readFile( | ||
join(__dirname, '..', '..', 'resources', 'head-end-modern.ejs'), | ||
'utf-8' | ||
); | ||
const bodyEndTemplate = await readFile( | ||
join(__dirname, '..', '..', 'resources', 'body-end-modern.ejs'), | ||
'utf-8' | ||
); | ||
const options = { | ||
url, | ||
manifest, | ||
ssr: () => { | ||
const params = { | ||
...data, | ||
CLI_DATA: { | ||
preRenderData: data, | ||
}, | ||
}; | ||
return prerender({ cwd, dest, src }, params); | ||
}, | ||
CLI_DATA: { url, ...routeData }, | ||
webpack, | ||
}; | ||
const htmlWebpackPlugin = { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. explain this |
||
options: { | ||
...options, | ||
title: title || manifest.name || manifest.short_name || 'Preact App', | ||
}, | ||
}; | ||
|
||
const headEnd = ejs.render(headEndTemplate, { | ||
options, | ||
htmlWebpackPlugin, | ||
}); | ||
|
||
const bodyEnd = ejs.render(bodyEndTemplate, { | ||
options, | ||
htmlWebpackPlugin, | ||
}); | ||
const template = templateSrc | ||
.replace(/<%[=]?\s+preact\.title\s+%>/, '<%= options.title %>') | ||
.replace(/<%\s+preact\.headEnd\s+%>/, headEnd) | ||
.replace(/<%\s+preact\.bodyEnd\s+%>/, bodyEnd); | ||
parentPort.postMessage({ | ||
url, | ||
content: minify( | ||
ejs.render(template, { | ||
options, | ||
htmlWebpackPlugin, | ||
}), | ||
{ | ||
collapseWhitespace: true, | ||
} | ||
), | ||
}); | ||
} | ||
|
||
if (!isMainThread) { | ||
const { src, dest, cwd, webpack, data } = workerData; | ||
render(src, dest, cwd, webpack, data); | ||
} |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<%- options.ssr() %> | ||
<% /* Fix for safari < 11 nomodule bug. TODO: Do the following only for safari. */ %> | ||
<script nomodule>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script> | ||
<script crossorigin="anonymous" src="<%= options.webpack.publicPath %><%= options.webpack.assets.find(entry => entry.match(/bundle(\.\w{5}).esm.js$/)) %>" type="module"></script> | ||
<% | ||
/*Fetch and Promise polyfills are not needed for browsers that support type=module | ||
Please re-evaluate below line if adding more polyfills.*/ | ||
%> | ||
<script nomodule src="<%= options.webpack.publicPath %><%= options.webpack.assets.find(entry => entry.match(/polyfills(\.\w{5}).esm.js$/)) %>"></script> | ||
<script nomodule defer src="<%= options.webpack.publicPath %><%= options.webpack.assets.find(entry => entry.match(/bundle(\.\w{5}).esm.js$/)) %>"></script> | ||
<script type="__PREACT_CLI_DATA__"> | ||
<%= encodeURI(JSON.stringify(options.CLI_DATA)) %> | ||
</script> |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
<link rel="manifest" href="<%= options.webpack.publicPath %>manifest.json"> | ||
<% if (options.manifest.theme_color) { %> | ||
<meta name="theme-color" content="<%= options.manifest.theme_color %>"> | ||
<% } %> | ||
|
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import { h } from 'preact'; | ||
|
||
export default () => <h2>This is an app with custom template</h2>; |
26 changes: 26 additions & 0 deletions
26
packages/cli/tests/subjects/experimental-rendering/manifest.json
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
{ | ||
"name": "Experimental renderer", | ||
"short_name": "Experimental renderer", | ||
"start_url": "/", | ||
"display": "standalone", | ||
"orientation": "portrait", | ||
"background_color": "#fff", | ||
"theme_color": "#fff", | ||
"icons": [ | ||
{ | ||
"src": "/assets/logo/android-chrome-192x192.png", | ||
"type": "image/png", | ||
"sizes": "192x192" | ||
}, | ||
{ | ||
"src": "/assets/logo/android-chrome-512x512.png", | ||
"type": "image/png", | ||
"sizes": "512x512" | ||
}, | ||
{ | ||
"src": "/assets/logo/apple-touch-icon.png", | ||
"type": "image/png", | ||
"sizes": "180x180" | ||
} | ||
] | ||
} |
4 changes: 4 additions & 0 deletions
4
packages/cli/tests/subjects/experimental-rendering/package.json
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"private": true, | ||
"name": "preact-webpack" | ||
} |
15 changes: 15 additions & 0 deletions
15
packages/cli/tests/subjects/experimental-rendering/template.html
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title><% preact.title %></title> | ||
<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
<meta name="mobile-web-app-capable" content="yes"> | ||
<meta name="apple-mobile-web-app-capable" content="yes"> | ||
<link rel="apple-touch-icon" href="/assets/icons/apple-touch-icon.png"> | ||
<% preact.headEnd %> | ||
</head> | ||
<body> | ||
<% preact.bodyEnd %> | ||
</body> | ||
</html> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
put copyright here