From adba2999bf4e8bc9394b6c78840319d8df1c140f Mon Sep 17 00:00:00 2001 From: Jeff Avallone Date: Thu, 15 Feb 2018 20:26:03 -0500 Subject: [PATCH] Updating prerender script to use async/await --- package.json | 2 ++ src/prerender.js | 29 ++++++++++++++++++++--------- yarn.lock | 6 ++++++ 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index d742458..6bca144 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/prerender.js b/src/prerender.js index d92d29e..fad2912 100644 --- a/src/prerender.js +++ b/src/prerender.js @@ -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()); - fs.writeFileSync(pagePath, markup.html()); + markup('#root').html(renderToString()); + 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); }); -}); diff --git a/yarn.lock b/yarn.lock index d6e1a39..2982caf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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"