How to generate static HTML using React
React is used to build web applications that run JavaScript in a user’s browser (client side rendering). It can also be used from a Node.js script to generate static HTML (static rendering).
Install Node.js
- $ brew install node
Set up project
Create a project directory and cd into it
$ mkdir my-project $ cd my-project
Create a
package.json
file:{ "scripts": { "render": "tsc && node dist/render.js" }, "dependencies": { "@types/node": "^14.0.4", "@types/prettier": "^2.0.0", "@types/react": "^16.9.35", "@types/react-dom": "^16.9.8", "prettier": "^2.0.5", "react": "^16.13.1", "react-dom": "^16.13.1", "typescript": "^3.9.3" } }
Install React, TypeScript, and other packages
$ npm install
Create a
tsconfig.json
file to configure TypeScript{ "compilerOptions": { "baseUrl": ".", "esModuleInterop": true, "jsx": "react", "lib": ["dom", "es2019"], "outDir": "dist", "paths": { "*": ["src/*", "src/@types/*"] } }, "include": ["src/*.tsx"] }
Create a script to generate a static HTML file
Create a directory,
src
and a filesrc/render.tsx
:import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactDOMServer from "react-dom/server"; render(); function render() { let html = ReactDOMServer.renderToStaticMarkup(<HelloWorldPage />); let htmlWDoc = "<!DOCTYPE html>" + html; let prettyHtml = prettier.format(htmlWDoc, { parser: "html" }); let outputFile = "./output.html"; fs.writeFileSync(outputFile, prettyHtml); console.log(`Wrote ${outputFile}`); } function HelloWorldPage() { return ( <html lang="en"> <head> <meta charSet="utf-8" /> <title>Hello world</title> </head> <body> <h1>Hello world</h1> </body> </html> ); }
Run the script and view the output
Run the script
$ npm run render
Open the
output.html
file in the browser$ open output.html
Read other posts