React is good and we love using it but we just don't want it inside our compiled HTML, CSS, and Javascript.
So, why do we talk about another method for static site generation instead of using these existing amazing tools?
{
"name": "react-no-react",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0"
},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.10.4",
"@babel/node": "^7.10.4",
"@babel/preset-env": "^7.9.5",
"@babel/preset-react": "^7.9.4",
"glob": "^7.1.6"
}
}
. ├── pages │ ├── AboutUs.jsx │ └── Home.jsx ├── scripts │ └── build.js ├── babel.config.js └── package.json
module.exports = {
presets: ["@babel/env", "@babel/react"],
};
import React from "react";
import path from "path";
import fs from "fs";
import glob from "glob";
import { renderToStaticMarkup } from "react-dom/server";
import { spawnSync } from "child_process";
const cwd = path.resolve(__dirname, "..");
// We glob all the files under "pages" directory
const reactFiles = glob.sync("pages/**/*.jsx", { cwd });
reactFiles.forEach((reactFile) => {
const fileName = path.basename(reactFile).replace(".jsx", "");
// Page components are from "default" export
const Component = require(path.resolve(__dirname, "../", reactFile)).default;
const staticMarkup = renderToStaticMarkup(<Component />);
// Generate HTML file name from ".jsx" files by replacing the extension with ".html"
const htmlFile = path.resolve(
__dirname,
"../dist/",
reactFile.replace(".jsx", ".html")
);
const dirName = path.dirname(htmlFile);
// In case we have nested page structure, we need to create directory recursively.
fs.mkdirSync(dirName, { recursive: true });
fs.writeFileSync(
htmlFile,
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>${fileName}</title>
</head>
<body>
${staticMarkup}
</body>
</html>`,
"utf8"
);
});
// pages/Home.jsx
import React from "react";
export default () => <h1>Home Page</h1>;
// pages/AboutUs.jsx
import React from "react";
export default () => <h1>About Us</h1>;
...
"scripts": {
"build": "babel-node scripts/build.js"
},
...
npm run build
yarn build
. ├── dist │ ├── AboutUs.html │ └── Home.html ...
From us to your inbox weekly.