Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@patrickarlt
Last active May 22, 2020 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickarlt/0feeab6770563845cb4d3ec2d2f32cd6 to your computer and use it in GitHub Desktop.
Save patrickarlt/0feeab6770563845cb4d3ec2d2f32cd6 to your computer and use it in GitHub Desktop.
Gatsby JS pre-rendering of Stencil components for Calcite Components.
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();
}
});
}
});
};
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