Skip to content

Instantly share code, notes, and snippets.

@tbremer
Last active August 23, 2019 04:45
Show Gist options
  • Save tbremer/c4d59261f19dff4360ee311cc92e7a79 to your computer and use it in GitHub Desktop.
Save tbremer/c4d59261f19dff4360ee311cc92e7a79 to your computer and use it in GitHub Desktop.
Build Static HTML site with React.

Static HTML from React

Simple static HTML builder for using React as the compiler.

Running

npx babel-node index.js or npm start

Project structure

All pages prefaced with _ are skipped

.
├── index.js
├── package-lock.json
├── package.json
└── pages
    ├── About.js
    ├── Home.js
    └── _page-wrapper.js

Output

.
├── dist
    ├── about.html
    └── index.html
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { existsSync, promises } from "fs";
const { writeFile, mkdir, readdir } = promises;
async function build() {
if (!existsSync("./dist/")) {
await mkdir("./dist");
}
const pages = await readdir("./pages").then(d =>
d.filter(p => !p.startsWith("_"))
);
for await (const page of pages) {
const file_name = page.replace(/\.js$/, "").toLowerCase();
const p = await import(`./pages/${page}`);
const html_string = `
<!DOCTYPE html>
${renderToStaticMarkup(createElement(p.default))}
`;
await writeFile(
file_name === "home" ? "dist/index.html" : `dist/${file_name}.html`,
html_string
);
}
}
build().then(() => console.log("Build Complete! 💅"));
{
"name": "static-react",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node index.js"
},
"keywords": [],
"author": "",
"browserslist": "> 1%",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/node": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@babel/preset-react": "^7.0.0",
"react": "^16.9.0",
"react-dom": "^16.9.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment