Last active
May 22, 2020 19:43
-
-
Save patrickarlt/0feeab6770563845cb4d3ec2d2f32cd6 to your computer and use it in GitHub Desktop.
Gatsby JS pre-rendering of Stencil components for Calcite Components.
This file contains hidden or 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
const path = require("path"); | |
const util = require("util"); | |
const glob = util.promisify(require("glob")); | |
const workerFarm = require("worker-farm"); | |
const workers = workerFarm(require.resolve("./hydrate-worker")); | |
// this runs as the last step after Gatsby has built the site/ | |
module.exports.onPostBuild = async function onPostBuild({ reporter }, { ignore }) { | |
const activity = reporter.activityTimer("Prerendering Calcite Components"); | |
activity.start(); | |
const publicPath = `./public`; | |
// get all HTML files | |
const files = await glob(path.join(publicPath, "**/*.html"), { ignore }); | |
let completed = 0; | |
return new Promise((resolve, reject) => { | |
for (let i = 0; i < files.length; i++) { | |
// send the path of each HTML file to the worker. | |
workers(files[i], error => { | |
if (error) { | |
activity.end(); | |
reject(error); | |
} | |
if (++completed === files.length) { | |
workerFarm.end(workers); | |
activity.end(); | |
resolve(); | |
} | |
}); | |
} | |
}); | |
}; |
This file contains hidden or 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
const hydrate = require("@esri/calcite-components/hydrate"); | |
const fs = require("fs"); | |
const util = require("util"); | |
const readFile = util.promisify(fs.readFile); | |
const writeFile = util.promisify(fs.writeFile); | |
module.exports = function(htmlPath, callback) { | |
// read the file run it through calcite components renderToString rewrite the result to disk. | |
readFile(htmlPath) | |
.then(buffer => hydrate.renderToString(buffer.toString())) | |
.then(result => { | |
writeFile(htmlPath, result.html); | |
}) | |
.then(() => { | |
callback(null); | |
}) | |
.catch(e => { | |
callback(null, e); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment