Updating prerender script to use async/await

This commit is contained in:
Jeff Avallone 2018-02-15 20:26:03 -05:00
parent 17e8be5f42
commit adba2999bf
3 changed files with 28 additions and 9 deletions

View File

@ -33,6 +33,7 @@
"react"
],
"plugins": [
"transform-runtime",
"transform-class-properties",
"syntax-dynamic-import"
]
@ -118,6 +119,7 @@
"babel-loader": "^7.1.2",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0",

View File

@ -1,20 +1,31 @@
import React from 'react';
import { renderToString } from 'react-dom/server';
import fs from 'fs';
import util from 'util';
import cheerio from 'cheerio';
import './i18n';
const pages = fs.readdirSync('./src/pages');
const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
pages.forEach(page => {
import(`./pages/${ page }/Component`).then(component => {
const Component = component.default;
const pagePath = `./build/${ page }.html`;
readdir('./src/pages')
.then(pages => (
Promise.all(pages.map(async page => {
const Component = (await import(`./pages/${ page }/Component`)).default;
const pagePath = `./build/${ page }.html`;
const markup = cheerio.load(fs.readFileSync(pagePath));
const markup = cheerio.load(await readFile(pagePath));
markup('#root').html(renderToString(<Component/>));
fs.writeFileSync(pagePath, markup.html());
markup('#root').html(renderToString(<Component/>));
await writeFile(pagePath, markup.html());
console.log(`${ page } prerendered`); // eslint-disable-line no-console
}))
))
.then(() => console.log('Done prerendering')) // eslint-disable-line no-console
.catch(e => {
console.log(e.toString()); // eslint-disable-line no-console
process.exit(1);
});
});

View File

@ -892,6 +892,12 @@ babel-plugin-transform-regenerator@^6.22.0:
dependencies:
regenerator-transform "^0.10.0"
babel-plugin-transform-runtime@^6.23.0:
version "6.23.0"
resolved "https://registry.yarnpkg.com/babel-plugin-transform-runtime/-/babel-plugin-transform-runtime-6.23.0.tgz#88490d446502ea9b8e7efb0fe09ec4d99479b1ee"
dependencies:
babel-runtime "^6.22.0"
babel-plugin-transform-strict-mode@^6.24.1:
version "6.24.1"
resolved "https://registry.yarnpkg.com/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz#d5faf7aa578a65bbe591cf5edae04a0c67020758"