fix: 并行渲染,提高效率

This commit is contained in:
Zhicheng WANG 2019-02-15 00:36:32 +08:00
parent 54c67e6294
commit a4fc5f8e37
2 changed files with 38 additions and 15 deletions

View File

@ -10,7 +10,7 @@ cd `dirname $0`
yarn build
yarn preview &
yarn preview > /tmp/preview.log &
sleep 3;

View File

@ -3,7 +3,8 @@ import * as klawSync from 'klaw-sync';
import { sync as mkdirp } from 'mkdirp';
import { minify } from 'html-minifier';
import { dirname, join } from 'path';
import { launch } from 'puppeteer';
import { Browser, launch, Request } from 'puppeteer';
import { chunk, uniq } from 'lodash';
const minifyOptions = {
collapseWhitespace: true,
@ -29,23 +30,45 @@ function getApiUrls(): string[] {
const urls = [...getGuideUrls(), ...getApiUrls(), 'index.html'];
async function prerender() {
const browser = await launch({ headless: false });
const page = await browser.newPage();
for (let i = 0; i < urls.length; ++i) {
const url = urls[i];
await page.goto(`http://localhost:4200/${url}`, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('#top-of-page');
const content = await page.content();
const filename = join('dist', `${url}.html`);
mkdirp(dirname(filename));
writeFileSync(filename, minify(content, minifyOptions), 'utf-8');
console.log(`rendered ${url}...`);
function filterResource(request: Request) {
const type = request.resourceType();
if (['image', 'stylesheet', 'font'].indexOf(type) !== -1) {
request.abort();
} else {
request.continue();
}
}
async function renderPage(browser: Browser, url: string) {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', filterResource);
await page.goto(`http://localhost:4200/${url}`, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('aio-doc-viewer>div');
const content = await page.content();
const filename = join('dist', `${url}.html`);
mkdirp(dirname(filename));
writeFileSync(filename, minify(content, minifyOptions), 'utf-8');
await page.close();
console.log(`rendered ${url}.`);
}
async function renderPageGroup(browser: Browser, urls: string[]) {
await Promise.all(urls.map(url => renderPage(browser, url)));
}
async function prerender() {
const browser = await launch({ defaultViewport: { width: 1280, height: 768 } });
const groups = chunk(uniq(urls), 4);
for (let i = 0; i < groups.length; ++i) {
await renderPageGroup(browser, groups[i]);
}
await browser.close();
}
prerender().then(() => {
process.exit(0);
}).catch(() => {
}).catch((e) => {
console.error(e);
process.exit(-1);
});