Skip to content

Instantly share code, notes, and snippets.

@Orbis25
Last active January 12, 2021 01:44
Show Gist options
  • Save Orbis25/f8f8cdda9fc4f5511437d0b7cc96b360 to your computer and use it in GitHub Desktop.
Save Orbis25/f8f8cdda9fc4f5511437d0b7cc96b360 to your computer and use it in GitHub Desktop.
server side rendering in reactjs with typescript
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator"
],
"presets": ["@babel/preset-react"]
}
require("core-js/stable");
require("regenerator-runtime/runtime")
require("ignore-styles");
require("@babel/register")({
ignore: [/(node_module)/],
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
extensions: [".js", ".jsx", ".ts", ".tsx"],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-nullish-coalescing-operator"
],
});
// server configuration
require("./server.tsx");
import React from "react";
import fs from "fs";
import express from "express";
import ReactDOMServer from "react-dom/server";
import App from "../src/App.tsx";
import path from "path";
const PORT = 8080;
const app = express();
app.use("^/$", (req, res, next) => {
const content = ReactDOMServer.renderToNodeStream(<App />)
fs.readFile(path.resolve("./build/index.html"), "utf-8", (err, data) => {
if (err) {
console.log(err);
return res.status(500).send("Some error happened");
}
return res.send(
data.replace(
"<div id='root'></div>",
`<div id='root'>${content}</div>`
)
);
});
});
app.use(express.static(path.resolve(__dirname, "..", "build")));
app.listen(PORT, () => {
console.log(`APP LAUNCHED ON PORT ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment